Class: AskTTY::SelectPrompt

Inherits:
Object
  • Object
show all
Defined in:
lib/asktty/prompts/select_prompt.rb

Constant Summary collapse

UNSET =
Object.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title:, options:, details: nil, value: UNSET, validator: nil) ⇒ SelectPrompt

Returns a new instance of SelectPrompt.



11
12
13
14
15
16
17
# File 'lib/asktty/prompts/select_prompt.rb', line 11

def initialize(title:, options:, details: nil, value: UNSET, validator: nil)
  @title = title.to_s
  @details = details&.to_s
  @options = Internal::Options.normalize(options)
  @index = index_for(value)
  @validator = validator
end

Class Method Details

.ask(title:, options:, details: nil, value: UNSET, &validator) ⇒ Object



7
8
9
# File 'lib/asktty/prompts/select_prompt.rb', line 7

def self.ask(title:, options:, details: nil, value: UNSET, &validator)
  new(title: title, details: details, options: options, value: value, validator: validator).ask
end

Instance Method Details

#askObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/asktty/prompts/select_prompt.rb', line 19

def ask
  validation_active = false

  Internal::Terminal.open do |session|
    loop do
      session.render(render(width: session.width, error_message: validation_message(validation_active)))

      case session.read_key
      when :enter
        validation_active = true
        next if validation_message(validation_active)

        session.render((width: session.width))
        return selected_option.value
      when :up, "k"
        previous_value = selected_option.value
        move(-1)
        validation_active ||= selected_option.value != previous_value
      when :down, "j"
        previous_value = selected_option.value
        move(1)
        validation_active ||= selected_option.value != previous_value
      end
    end
  end
end