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 16
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
  }
  @pause   = true
  @countdown = @timeout
  @interval_handler = proc { |time|
    question = render_question
    @prompt.print(refresh(question.lines.count))
    countdown(time)
    @prompt.print(render_question)
  }

  @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 42
def any_key?
  @keys == UndefinedSetting
end
countdown(value = (not_set = true)) click to toggle source
# File lib/tty/prompt/keypress.rb, line 36
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 51
def keypress(event)
  if any_key?
    @pause = false
  elsif @keys.is_a?(Array) && @keys.include?(event.key.name)
    @pause = false
  else
    @pause = true
  end
end
process_input(question) click to toggle source
# File lib/tty/prompt/keypress.rb, line 67
def process_input(question)
  time do
    while @pause
      @input = @prompt.read_keypress
    end
    @pause
  end
  @evaluator.(@input)
end
refresh(lines) click to toggle source
# File lib/tty/prompt/keypress.rb, line 77
def refresh(lines)
  @prompt.clear_lines(lines)
end
render_question() click to toggle source
Calls superclass method
# File lib/tty/prompt/keypress.rb, line 61
def render_question
  header = super
  header.gsub!(/:countdown/, countdown.to_s)
  header
end
time(&block) click to toggle source
# File lib/tty/prompt/keypress.rb, line 81
def time(&block)
  if timeout?
    time = Float(@timeout)
    interval = Float(@interval)
    scheduler = Timeout.new(interval_handler: @interval_handler)
    scheduler.timeout(time, interval, &block)
  else
    block.()
  end
rescue Timeout::Error
end
timeout?() click to toggle source

Check if timeout is set

# File lib/tty/prompt/keypress.rb, line 47
def timeout?
  @timeout != UndefinedSetting
end