Class: Hirb::Menu
- Inherits:
-
Object
- Object
- Hirb::Menu
- Defined in:
- lib/hirb/menu.rb
Overview
This class provides a selection menu using Hirb’s table helpers by default to display choices.
Class Method Summary collapse
-
.choose_from_menu(output, options) ⇒ Object
:nodoc:.
-
.render(output, options = {}) {|chosen| ... } ⇒ Object
Menu which asks to select from the given array and returns the selected menu items as an array.
Class Method Details
.choose_from_menu(output, options) ⇒ Object
:nodoc:
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/hirb/menu.rb', line 26 def self.(output, ) #:nodoc: return output if output.size == 1 && ![:ask] if (helper_class = Util.any_const_get([:helper_class])) View.render_output(output, :class=>[:helper_class], :options=>.merge(:number=>true)) else output.each_with_index {|e,i| puts "#{i+1}: #{e}" } end print [:prompt] input = $stdin.gets.chomp.strip chosen = Util.choose_from_array(output, input) if [:validate_one] if chosen.size != 1 $stderr.puts "Choose one. You chose #{chosen.size} items." return nil else return chosen[0] end end chosen end |
.render(output, options = {}) {|chosen| ... } ⇒ Object
Menu which asks to select from the given array and returns the selected menu items as an array. See Hirb::Util.choose_from_array for the syntax for specifying selections. All options except for the ones below are passed to render the menu.
Options:
- :helper_class
-
Helper class to render menu. Helper class is expected to implement numbering given a :number option. To use a very basic menu, set this to false. Defaults to Hirb::Helpers::AutoTable.
- :prompt
-
String for menu prompt. Defaults to “Choose: ”.
- :validate_one
-
Validates that only one item in array is chosen and returns just that item. Default is false.
- :ask
-
Always ask for input, even if there is only one choice. Default is true.
Examples:
extend Hirb::Console
([1,2,3], :fields=>[:field1, :field2], :validate_one=>true)
([1,2,3], :helper_class=>Hirb::Helpers::Table)
17 18 19 20 21 22 23 24 |
# File 'lib/hirb/menu.rb', line 17 def self.render(output, ={}) = {:helper_class=>Hirb::Helpers::AutoTable, :prompt=>"Choose #{[:validate_one] ? 'one' : ''}: ", :ask=>true} = .merge() output = [output] unless output.is_a?(Array) chosen = (output, ) yield(chosen) if block_given? && chosen.is_a?(Array) && chosen.size > 0 chosen end |