Class HighLine::Menu
In: lib/highline/menu.rb
Parent: Question
HighLine\n[lib/highline.rb\nlib/highline/color_scheme.rb\nlib/highline/menu.rb\nlib/highline/question.rb\nlib/highline/system_extensions.rb] HighLine::SystemExtensions dot/f_6.png

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.

Methods

choice   choices   help   hidden   index=   init_help   layout=   new   options   select   to_ary   to_str   update_responses  

Attributes

flow  [RW]  This attribute is passed directly on as the mode to HighLine.list() by all the preset layouts. See that method for appropriate settings.
header  [RW]  Used by all the preset layouts to display title and/or introductory information, when set. Defaults to nil.
index  [R]  An index to append to each menu item in display. See Menu.index=() for details.
index_suffix  [RW]  The String placed between an index and a menu item. Defaults to ". ". Switches to " ", when index is set to a String (like "-").
layout  [R]  An ERb layout to use when displaying this Menu object. See Menu.layout=() for details.
list_option  [RW]  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.
nil_on_handled  [RW]  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.
prompt  [RW]  Used by all the preset layouts to ask the actual question to fetch a menu selection from the user. Defaults to "? ".
select_by  [RW]  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.
shell  [RW]  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.

Public Class methods

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.

[Source]

    # File lib/highline/menu.rb, line 26
26:     def initialize(  )
27:       #
28:       # Initialize Question objects with ignored values, we'll
29:       # adjust ours as needed.
30:       # 
31:       super("Ignored", [ ], &nil)    # avoiding passing the block along
32:       
33:       @items           = [ ]
34:       @hidden_items    = [ ]
35:       @help            = Hash.new("There's no help for that topic.")
36: 
37:       @index           = :number
38:       @index_suffix    = ". "
39:       @select_by       = :index_or_name
40:       @flow            = :rows
41:       @list_option     = nil
42:       @header          = nil
43:       @prompt          = "?  "
44:       @layout          = :list
45:       @shell           = false
46:       @nil_on_handled  = false
47:       
48:       # Override Questions responses, we'll set our own.
49:       @responses       = { }
50:       # Context for action code.
51:       @highline        = nil
52:       
53:       yield self if block_given?
54: 
55:       init_help if @shell and not @help.empty?
56:       update_responses     # rebuild responses based on our settings
57:     end

Public Instance methods

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. The @highline variable is set to the current HighLine context before the action code is called and can thus be used for adding output and the like.

[Source]

     # File lib/highline/menu.rb, line 139
139:     def choice( name, help = nil, &action )
140:       @items << [name, action]
141:       
142:       @help[name.to_s.downcase] = help unless help.nil?
143:     end

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.

[Source]

     # File lib/highline/menu.rb, line 151
151:     def choices( *names, &action )
152:       names.each { |n| choice(n, &action) }
153:     end

Used to set help for arbitrary topics. Use the topic "help" to override the default message.

[Source]

     # File lib/highline/menu.rb, line 216
216:     def help( topic, help )
217:       @help[topic] = help
218:     end

Identical to choice(), but the item will not be listed for the user.

[Source]

     # File lib/highline/menu.rb, line 156
156:     def hidden( name, help = nil, &action )
157:       @hidden_items << [name, action]
158:       
159:       @help[name.to_s.downcase] = help unless help.nil?
160:     end

Sets the indexing style for this Menu object. Indexes are appended to menu items, when displayed in list form. The available settings are:

:number:Menu items will be indexed numerically, starting with 1. This is the default method of indexing.
:letter:Items will be indexed alphabetically, starting with a.
:none:No index will be appended to menu items.
any String:Will be used as the literal index.

Setting the index to :none a literal String, also adjusts index_suffix to a single space and select_by to :none. Because of this, you should make a habit of setting the index first.

[Source]

     # File lib/highline/menu.rb, line 177
177:     def index=( style )
178:       @index = style
179:       
180:       # Default settings.
181:       if @index == :none or @index.is_a?(String)
182:         @index_suffix = " "
183:         @select_by    = :name
184:       end
185:     end

Initializes the help system by adding a :help choice, some action code, and the default help listing.

[Source]

     # File lib/highline/menu.rb, line 191
191:     def init_help(  )
192:       return if @items.include?(:help)
193:       
194:       topics    = @help.keys.sort
195:       help_help = @help.include?("help") ? @help["help"] :
196:                   "This command will display helpful messages about " +
197:                   "functionality, like this one.  To see the help for " +
198:                   "a specific topic enter:\n\thelp [TOPIC]\nTry asking " +
199:                   "for help on any of the following:\n\n" +
200:                   "<%= list(#{topics.inspect}, :columns_across) %>"
201:       choice(:help, help_help) do |command, topic|
202:         topic.strip!
203:         topic.downcase!
204:         if topic.empty?
205:           @highline.say(@help["help"])
206:         else
207:           @highline.say("= #{topic}\n\n#{@help[topic]}")
208:         end
209:       end
210:     end

Setting a layout with this method also adjusts some other attributes of the Menu object, to ideal defaults for the chosen layout. To account for that, you probably want to set a layout first in your configuration block, if needed.

Accepted settings for layout are:

:list:The default layout. The header if set will appear at the top on its own line with a trailing colon. Then the list of menu items will follow. Finally, the prompt will be used as the ask()-like question.
:one_line:A shorter layout that fits on one line. The header comes first followed by a colon and spaces, then the prompt with menu items between trailing parenthesis.
:menu_only:Just the menu items, followed up by a likely short prompt.
any ERb String:Will be taken as the literal layout. This String can access @header, @menu and @prompt, but is otherwise evaluated in the typical HighLine context, to provide access to utilities like HighLine.list() primarily.

If set to either :one_line, or :menu_only, index will default to :none and flow will default to :inline.

[Source]

     # File lib/highline/menu.rb, line 250
250:     def layout=( new_layout )
251:       @layout = new_layout
252:       
253:       # Default settings.
254:       case @layout
255:       when :one_line, :menu_only
256:         self.index = :none
257:         @flow  = :inline
258:       end
259:     end

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

[Source]

     # File lib/highline/menu.rb, line 265
265:     def options(  )
266:       # add in any hidden menu commands
267:       @items.concat(@hidden_items)
268:       
269:       by_index = if @index == :letter
270:         l_index = "`"
271:         @items.map { "#{l_index.succ!}" }
272:       else
273:         (1 .. @items.size).collect { |s| String(s) }
274:       end
275:       by_name = @items.collect { |c| c.first }
276: 
277:       case @select_by
278:       when :index then
279:         by_index
280:       when :name
281:         by_name
282:       else
283:         by_index + by_name
284:       end
285:     ensure
286:       # make sure the hidden items are removed, before we return
287:       @items.slice!(@items.size - @hidden_items.size, @hidden_items.size)
288:     end

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

[Source]

     # File lib/highline/menu.rb, line 295
295:     def select( highline_context, selection, details = nil )
296:       # add in any hidden menu commands
297:       @items.concat(@hidden_items)
298:       
299:       # Find the selected action.
300:       name, action = if selection =~ /^\d+$/
301:         @items[selection.to_i - 1]
302:       else
303:         l_index = "`"
304:         index = @items.map { "#{l_index.succ!}" }.index(selection)
305:         @items.find { |c| c.first == selection } or @items[index]
306:       end
307:       
308:       # Run or return it.
309:       if not @nil_on_handled and not action.nil?
310:         @highline = highline_context
311:         if @shell
312:           action.call(name, details)
313:         else
314:           action.call(name)
315:         end
316:       elsif action.nil?
317:         name
318:       else
319:         nil
320:       end
321:     ensure
322:       # make sure the hidden items are removed, before we return
323:       @items.slice!(@items.size - @hidden_items.size, @hidden_items.size)
324:     end

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

[Source]

     # File lib/highline/menu.rb, line 331
331:     def to_ary(  )
332:       case @index
333:       when :number
334:         @items.map { |c| "#{@items.index(c) + 1}#{@index_suffix}#{c.first}" }
335:       when :letter
336:         l_index = "`"
337:         @items.map { |c| "#{l_index.succ!}#{@index_suffix}#{c.first}" }
338:       when :none
339:         @items.map { |c| "#{c.first}" }
340:       else
341:         @items.map { |c| "#{index}#{@index_suffix}#{c.first}" }
342:       end
343:     end

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

[Source]

     # File lib/highline/menu.rb, line 349
349:     def to_str(  )
350:       case @layout
351:       when :list
352:         '<%= if @header.nil? then '' else "#{@header}:\n" end %>' +
353:         "<%= list( @menu, #{@flow.inspect},
354:                           #{@list_option.inspect} ) %>" +
355:         "<%= @prompt %>"
356:       when :one_line
357:         '<%= if @header.nil? then '' else "#{@header}:  " end %>' +
358:         "<%= @prompt %>" +
359:         "(<%= list( @menu, #{@flow.inspect},
360:                            #{@list_option.inspect} ) %>)" +
361:         "<%= @prompt[/\s*$/] %>"
362:       when :menu_only
363:         "<%= list( @menu, #{@flow.inspect},
364:                           #{@list_option.inspect} ) %><%= @prompt %>"
365:       else
366:         @layout
367:       end
368:     end

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

[Source]

     # File lib/highline/menu.rb, line 375
375:     def update_responses(  )
376:       append_default unless default.nil?
377:       @responses = { :ambiguous_completion =>
378:                        "Ambiguous choice.  " +
379:                        "Please choose one of #{options.inspect}.",
380:                      :ask_on_error         =>
381:                        "?  ",
382:                      :invalid_type         =>
383:                        "You must enter a valid #{options}.",
384:                      :no_completion        =>
385:                        "You must choose one of " +
386:                        "#{options.inspect}.",
387:                      :not_in_range         =>
388:                        "Your answer isn't within the expected range " +
389:                        "(#{expected_range}).",
390:                      :not_valid            =>
391:                        "Your answer isn't valid (must match " +
392:                        "#{@validate.inspect})." }.merge(@responses)
393:     end

[Validate]