Class: HighLine::Menu

Inherits:
Question show all
Defined in:
lib/highline/menu.rb

Overview

Menu objects encapsulate all the details of a call to HighLine.choose(). Using the accessors and Menu.choice() and Menu.choices(), the block passed to HighLine.choose() can detail all aspects of menu display and control.

Instance Attribute Summary collapse

Attributes inherited from Question

#above, #answer_type, #below, #case, #character, #confirm, #default, #echo, #in, #responses, #validate, #whitespace

Instance Method Summary collapse

Methods inherited from Question

#answer_or_default, #build_responses, #change_case, #convert, #expected_range, #in_range?, #remove_whitespace, #valid_answer?

Constructor Details

#initialize {|_self| ... } ⇒ Menu

Create an instance of HighLine::Menu. All customization is done through the passed block, which should call accessors and choice() and choices() as needed to define the Menu. Note that Menus are also Questions, so all that functionality is available to the block as well.

Yields:

  • (_self)

Yield Parameters:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/highline/menu.rb', line 24

def initialize(  )
	#
	# Initialize Question objects with ignored valued, we'll
	# adjust ours as needed.
	# 
	super("Ignored", [ ], &nil)    # avoiding passing to block along
	
	@items           = [ ]

	@index           = :number
	@index_suffix    = ". "
	@select_by       = :index_or_name
	@flow            = :rows
	@list_option     = nil
	@header          = nil
	@prompt          = "?  "
	@layout          = :list
	@shell           = false
	@nil_on_handled  = false
	
	# Override Questions repsonses, we'll set our own.
	@responses       = { }
	
	yield self if block_given?

	update_responses     # rebuild responses based on our settings
end

Instance Attribute Details

#flowObject

This attribute is passed directly on as the mode to HighLine.list() by all the preset layouts. See that method for appropriate settings.



80
81
82
# File 'lib/highline/menu.rb', line 80

def flow
  @flow
end

#headerObject

Used by all the preset layouts to display title and/or introductory information, when set. Defaults to nil.



91
92
93
# File 'lib/highline/menu.rb', line 91

def header
  @header
end

#indexObject

An index to append to each menu item in display. See Menu.index=() for details.



56
57
58
# File 'lib/highline/menu.rb', line 56

def index
  @index
end

#index_suffixObject

The String placed between an index and a menu item. Defaults to “. ”. Switches to “ ”, when index is set to a String (like “-”).



61
62
63
# File 'lib/highline/menu.rb', line 61

def index_suffix
  @index_suffix
end

#layoutObject

An ERb layout to use when displaying this Menu object. See Menu.layout=() for details.



101
102
103
# File 'lib/highline/menu.rb', line 101

def layout
  @layout
end

#list_optionObject

This setting is passed on as the third parameter to HighLine.list() by all the preset layouts. See that method for details of its effects. Defaults to nil.



86
87
88
# File 'lib/highline/menu.rb', line 86

def list_option
  @list_option
end

#nil_on_handledObject

When true, any selected item handled by provided action code, will return nil, instead of the results to the action code. This may prove handy when dealing with mixed menus where only the names of items without any code (and nil, of course) will be returned. Defaults to false.



117
118
119
# File 'lib/highline/menu.rb', line 117

def nil_on_handled
  @nil_on_handled
end

#promptObject

Used by all the preset layouts to ask the actual question to fetch a menu selection from the user. Defaults to “? ”.



96
97
98
# File 'lib/highline/menu.rb', line 96

def prompt
  @prompt
end

#select_byObject

The select_by attribute controls how the user is allowed to pick a menu item. The available choices are:

:index

The user is allowed to type the numerical or alphetical index for their selection.

:index_or_name

Allows both methods from the :index option and the :name option.

:name

Menu items are selected by typing a portion of the item name that will be auto-completed.



75
76
77
# File 'lib/highline/menu.rb', line 75

def select_by
  @select_by
end

#shellObject

When set to true, responses are allowed to be an entire line of input, including details beyond the command itself. Only the first “word” of input will be matched against the menu choices, but both the command selected and the rest of the line will be passed to provided action blocks. Defaults to false.



109
110
111
# File 'lib/highline/menu.rb', line 109

def shell
  @shell
end

Instance Method Details

#choice(name, &action) ⇒ Object

Adds name to the list of available menu items. Menu items will be displayed in the order they are added.

An optional action can be associated with this name and if provided, it will be called if the item is selected. The result of the method will be returned, unless nil_on_handled is set (when you would get nil instead). In shell mode, a provided block will be passed the command chosen and any details that followed the command. Otherwise, just the command is passed.



130
131
132
# File 'lib/highline/menu.rb', line 130

def choice( name, &action )
	@items << [name, action]
end

#choices(*names, &action) ⇒ Object

A shortcut for multiple calls to the sister method choice(). Be warned: An action set here will apply to all provided names. This is considered to be a feature, so you can easily hand-off interface processing to a different chunk of code.



140
141
142
# File 'lib/highline/menu.rb', line 140

def choices( *names, &action )
	names.each { |n| choice(n, &action) }
end

#optionsObject

This method returns all possible options for auto-completion, based on the settings of index and select_by.



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/highline/menu.rb', line 214

def options(  )
		by_index = if @index == :letter
				l_index = "`"
				@items.map { "#{l_index.succ!}" }
			else
				(1 .. @items.size).collect { |s| String(s) }
			end
	by_name  = @items.collect { |c| c.first }

		case @select_by
			when :index then
				by_index
			when :name
				by_name
			else
				by_index + by_name
			end
end

#select(selection, details = nil) ⇒ Object

This method processes the auto-completed user selection, based on the rules for this Menu object. It an action was provided for the selection, it will be executed as described in Menu.choice().



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/highline/menu.rb', line 238

def select( selection, details = nil )
	# Find the selected action.
	name, action = if selection =~ /^\d+$/
		@items[selection.to_i - 1]
	else
		l_index = "`"
		index = @items.map { "#{l_index.succ!}" }.index(selection)
		@items.find { |c| c.first == selection } or @items[index]
	end
	
	# Run or return it.
	if not @nil_on_handled and not action.nil?
		if @shell
			action.call(name, details)
		else
			action.call(name)
		end
	elsif action.nil?
		name
	else
		nil
	end
end

#to_aryObject

Allows Menu objects to pass as Arrays, for use with HighLine.list(). This method returns all menu items to be displayed, complete with indexes.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/highline/menu.rb', line 267

def to_ary(  )
	case @index
	when :number
		@items.map do |c|
			"#{@items.index(c) + 1}#{@index_suffix}#{c.first}"
		end
	when :letter
		l_index = "`"
		@items.map { |c| "#{l_index.succ!}#{@index_suffix}#{c.first}" }
	when :none
		@items.map { |c| "#{c.first}" }
	else
		@items.map { |c| "#{index}#{@index_suffix}#{c.first}" }
	end
end

#to_strObject

Allows Menu to behave as a String, just like Question. Returns the layout to be rendered, which is used by HighLine.say().



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/highline/menu.rb', line 287

def to_str(  )
	case @layout
	when :list
		'<%= if @header.nil? then '' else "#{@header}:\n" end %>' +
		"<%= list( @menu, #{@flow.inspect},
		                  #{@list_option.inspect} ) %>" +
		"<%= @prompt %>"
	when :one_line
		'<%= if @header.nil? then '' else "#{@header}:  " end %>' +
		"<%= @prompt %>" +
		"(<%= list( @menu, #{@flow.inspect},
		                   #{@list_option.inspect} ) %>)" +
		"<%= @prompt[/\s*$/] %>"
	when :menu_only
		"<%= list( @menu, #{@flow.inspect},
		                  #{@list_option.inspect} ) %><%= @prompt %>"
	else
		@layout
	end
end

#update_responsesObject

This method will update the intelligent responses to account for Menu specific differences. This overrides the work done by Question.build_responses().



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/highline/menu.rb', line 313

def update_responses(  )
	append_default unless default.nil?
	@responses = { :ambiguous_completion =>
	                   "Ambiguous choice.  " +
	                   "Please choose one of #{options.inspect}.",
	               :ask_on_error         =>
	                   "?  ",
	               :invalid_type         =>
	                   "You must enter a valid #{options}.",
	               :no_completion        =>
	                   "You must choose one of " +
	                   "#{options.inspect}.",
	               :not_in_range         =>
	                   "Your answer isn't within the expected range " +
	                   "(#{expected_range}).",
	               :not_valid            =>
	                   "Your answer isn't valid (must match " +
	                   "#{@validate.inspect})." }.merge(@responses)
end