Module: Menu
Constant Summary collapse
- VERSION =
'0.1.0'
Instance Method Summary collapse
- #ask ⇒ Object
- #parse_answer(array, input) ⇒ Object
- #prompt(lines) ⇒ Object
- #run(lines = ARGV) ⇒ Object
Instance Method Details
#ask ⇒ Object
22 23 24 25 |
# File 'lib/menu.rb', line 22 def ask $stdin.reopen '/dev/tty' $stdin.gets.chomp end |
#parse_answer(array, input) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/menu.rb', line 27 def parse_answer(array, input) return array if input.strip == '*' result = [] input.split(/\s*,\s*/).each do |e| if e[/(\d+)-(\d+)/] min, max = $1, $2 slice_min = min.to_i - 1 result.push(*array.slice(slice_min, max.to_i - min.to_i + 1)) elsif e[/^(\d+)$/] index = $1.to_i - 1 result.push(array[index]) if array[index] else abort("`#{e}' is an invalid choice.") end end result end |
#prompt(lines) ⇒ Object
13 14 15 16 17 18 19 20 |
# File 'lib/menu.rb', line 13 def prompt(lines) ljust_size = lines.size.to_s.size + 1 lines.each_with_index {|obj,i| puts "#{i+1}.".ljust(ljust_size) + " " +obj } print "\nSpecify individual choices (4,7), range of choices (1-3)" + " or all choices (*).\nChoose: " end |
#run(lines = ARGV) ⇒ Object
6 7 8 9 10 11 |
# File 'lib/menu.rb', line 6 def run(lines=ARGV) lines = $stdin.read.split("\n") if !$stdin.tty? prompt(lines) answer = ask puts parse_answer(lines, answer) end |