Class: Amp::UIMenu

Inherits:
Object show all
Defined in:
lib/amp/support/amp_ui.rb

Overview

Represents an extremely simple menu that the UI can use to ask for input. Replacement for Highline’s “choose” method - and is extremely, extremely basic. In fact, I might strip out some flexibility for now. I just did. It only does numbered lists with no intelligently figuring things out.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUIMenu

Creates a new UIMenu. Initializes ivars. Does nothing else of use.



20
21
22
23
24
# File 'lib/amp/support/amp_ui.rb', line 20

def initialize
  @choices = []
  @prompt = "Pick an option, please."
  @index = :number
end

Instance Attribute Details

#indexObject

How to index results - left in for compatibility and possibly future flexibility



14
15
16
# File 'lib/amp/support/amp_ui.rb', line 14

def index
  @index
end

#promptObject

The prompt to ask at the top of the menu



12
13
14
# File 'lib/amp/support/amp_ui.rb', line 12

def prompt
  @prompt
end

Instance Method Details

#choice(prompt, opts = {}, &block) ⇒ Object

Adds a choice to the list of choices to be presented to the user. Choices are ordered in the order in which this method is called. The block is stored and executed if the choice is selected.

Parameters:

  • prompt (String)

    the prompt to display to the user for this choice

  • opts (Hash) (defaults to: {})

    options for this choice (unused for now)

  • &block (Proc)

    a block that will be executed later if the choice is selected



36
37
38
# File 'lib/amp/support/amp_ui.rb', line 36

def choice(prompt, opts={}, &block)
  @choices << {:text => prompt, :action => block}
end

#runObject

Runs the UIMenu. Will loop until an acceptable choice is selected by the user. Prints the choices in the order in which they were added, in a numbered list. The user must select the number of their desired option. After an acceptable choice is selected, its associated block is executed.



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/amp/support/amp_ui.rb', line 46

def run
  input = -1
  while input <= 0 || input > @choices.size do
    UI.say @prompt
    @choices.each_with_index {|item, idx| UI::say "#{idx+1} #{item[:text]}"}
    UI::say
    UI::tell "Your choice: "
    UI::say "[1-#{@choices.size}]"
    input = UI::ask('', Integer)
  end
  choice = @choices[input - 1]
  choice[:action].call
end