Class: Question::List

Inherits:
Object
  • Object
show all
Defined in:
lib/question/list.rb

Instance Method Summary collapse

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

#askObject



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_inputObject



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

#instructionsObject



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

#renderObject



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