Class: Achoo::Term::Menu

Inherits:
Object
  • Object
show all
Defined in:
lib/achoo/term/menu.rb

Instance Method Summary collapse

Constructor Details

#initialize(question, entries, special = nil, additional_valid_answers = []) ⇒ Menu

Returns a new instance of Menu.



7
8
9
10
11
12
13
14
15
16
# File 'lib/achoo/term/menu.rb', line 7

def initialize(question, entries, special=nil, additional_valid_answers=[])
  @question = question
  @entries  = entries
  @special  = special

  @valid = {}
  @valid['0'] = true unless @special.nil?
  1.upto(@entries.length).each {|i| @valid[i.to_s] = true}
  additional_valid_answers.each {|a| @valid[a] = true}
end

Instance Method Details



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/achoo/term/menu.rb', line 18

def print_ask_and_validate()
  return nil if @entries.empty?

  print_menu()
  return '1' if only_one_option?
  
  loop do
    answer = Term.ask(@question)
    if @valid[answer]
      return answer
    else
      puts "Invalid value. Must be one of " << @valid.keys.sort.join(',')
    end
  end
end