Class: Question::List
- Inherits:
-
Object
- Object
- Question::List
- Defined in:
- lib/question/list.rb
Instance Method Summary collapse
- #ask ⇒ Object
- #handle_input ⇒ Object
-
#initialize(question, choices) ⇒ List
constructor
A new instance of List.
- #instructions ⇒ Object
- #label_for_choice(choice) ⇒ Object
- #render ⇒ Object
- #value_for_choice(choice) ⇒ Object
Constructor Details
#initialize(question, choices) ⇒ List
Returns a new instance of List.
3 4 5 6 7 8 |
# File 'lib/question/list.rb', line 3 def initialize(question, choices) @question = question @choices = choices @active_index = 0 @finished = false end |
Instance Method Details
#ask ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/question/list.rb', line 18 def ask TTY.interactive do while !@finished render handle_input end render end value_for_choice(@choices[@active_index]) end |
#handle_input ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/question/list.rb', line 30 def handle_input case TTY.input when TTY::CODE::SIGINT exit 130 when TTY::CODE::RETURN, TTY::CODE::SPACE @finished = true when TTY::CODE::DOWN, TTY::CODE::CTRL_J, TTY::CODE::CTRL_N @active_index += 1 @active_index = 0 if @active_index >= @choices.length when TTY::CODE::UP, TTY::CODE::CTRL_K, TTY::CODE::CTRL_P @active_index -= 1 @active_index = @choices.length - 1 if @active_index < 0 end end |
#instructions ⇒ Object
45 46 47 |
# File 'lib/question/list.rb', line 45 def instructions "(Press <enter> to select item)" end |
#label_for_choice(choice) ⇒ Object
10 11 12 |
# File 'lib/question/list.rb', line 10 def label_for_choice(choice) choice.is_a?(Hash) ? choice[:label] : choice end |
#render ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/question/list.rb', line 49 def render TTY.clear print "? ".cyan print @question print ": " if @finished print label_for_choice(@choices[@active_index]).green else print instructions.light_black end print "\n" unless @finished @choices.each_with_index do |choice, index| print index == @active_index ? TTY::UI::SELECTED.green : TTY::UI::UNSELECTED print " " if index == @active_index print label_for_choice(choice).green else print label_for_choice(choice) end print "\n" end print TTY::CODE::NOOP end end |
#value_for_choice(choice) ⇒ Object
14 15 16 |
# File 'lib/question/list.rb', line 14 def value_for_choice(choice) choice.is_a?(Hash) ? choice[:value] : choice end |