class TTY::Prompt::Keypress
Public Class Methods
new(prompt, options = {})
click to toggle source
Create keypress question
@param [Prompt] prompt @param [Hash] options
@api public
Calls superclass method
# File lib/tty/prompt/keypress.rb, line 15 def initialize(prompt, options = {}) super @echo = options.fetch(:echo) { false } @keys = options.fetch(:keys) { UndefinedSetting } @timeout = options.fetch(:timeout) { UndefinedSetting } @interval = options.fetch(:interval) { (@timeout != UndefinedSetting && @timeout < 1) ? @timeout : 1 } @countdown = @timeout @interval_handler = proc { |time| unless @done question = render_question line_size = question.size total_lines = @prompt.count_screen_lines(line_size) @prompt.print(refresh(question.lines.count, total_lines)) countdown(time) @prompt.print(render_question) end } @scheduler = Timeout.new(interval_handler: @interval_handler) @prompt.subscribe(self) end
Public Instance Methods
any_key?()
click to toggle source
Check if any specific keys are set
# File lib/tty/prompt/keypress.rb, line 45 def any_key? @keys == UndefinedSetting end
countdown(value = (not_set = true))
click to toggle source
# File lib/tty/prompt/keypress.rb, line 39 def countdown(value = (not_set = true)) return @countdown if not_set @countdown = value end
keypress(event)
click to toggle source
# File lib/tty/prompt/keypress.rb, line 54 def keypress(event) if any_key? @done = true @scheduler.cancel elsif @keys.is_a?(Array) && @keys.include?(event.key.name) @done = true @scheduler.cancel else @done = false end end
process_input(question)
click to toggle source
# File lib/tty/prompt/keypress.rb, line 72 def process_input(question) time do @prompt.print(render_question) until @done @input = @prompt.read_keypress(nonblock: true) end end @evaluator.(@input) end
refresh(lines, lines_to_clear)
click to toggle source
# File lib/tty/prompt/keypress.rb, line 82 def refresh(lines, lines_to_clear) @prompt.clear_lines(lines) end
render_question()
click to toggle source
Calls superclass method
# File lib/tty/prompt/keypress.rb, line 66 def render_question header = super header.gsub!(/:countdown/, countdown.to_s) header end
time(&job)
click to toggle source
Wait for keypress or timeout
@api private
# File lib/tty/prompt/keypress.rb, line 89 def time(&job) if timeout? time = Float(@timeout) interval = Float(@interval) @scheduler.timeout(time, interval, &job) else job.() end rescue Timeout::Error end
timeout?()
click to toggle source
Check if timeout is set
# File lib/tty/prompt/keypress.rb, line 50 def timeout? @timeout != UndefinedSetting end