Class: TTY::MenuTree::Menu

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/menu_tree/menu.rb

Overview

Runs a tree of actions as an interactive, hierarchical menu.

The loop repeatedly asks the user to pick an action. Leaf actions are invoked via #call; actions that expose a #submenu are descended into (with a "Back" entry); and an action whose #exit? returns true ends the loop.

Examples:

menu = TTY::MenuTree::Menu.new(
  actions: [group, TTY::MenuTree::ExitAction.new],
  title: "What would you like to do?",
  on_start: -> { puts "Welcome!" },
  on_exit: -> { puts "Goodbye!" },
)
menu.run

Instance Method Summary collapse

Constructor Details

#initialize(actions:, prompt: Prompt.new, title: "What would you like to do?", on_start: nil, on_exit: nil) ⇒ Menu

Returns a new instance of Menu.

Parameters:

  • actions (Array<#name>) —

    top-level actions.

  • prompt (#select_action) (defaults to: Prompt.new) —

    object used to render menus. Defaults to a Prompt.

  • title (String) (defaults to: "What would you like to do?") —

    heading shown for the top-level menu each loop.

  • on_start (#call, nil) (defaults to: nil) —

    callable run once before the loop starts.

  • on_exit (#call, nil) (defaults to: nil) —

    callable run once after an exit action is chosen.



30
31
32
33
34
35
36
37
# File 'lib/tty/menu_tree/menu.rb', line 30

def initialize(actions:, prompt: Prompt.new, title: "What would you like to do?",
               on_start: nil, on_exit: nil)
  @actions = actions
  @prompt = prompt
  @title = title
  @on_start = on_start
  @on_exit = on_exit
end

Instance Method Details

#run ⇒ void

This method returns an undefined value.

Run the interactive loop until an exit action is chosen.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tty/menu_tree/menu.rb', line 41

def run
  @on_start&.call

  loop do
    action = @prompt.select_action(@title, @actions)

    if action.exit?
      @on_exit&.call
      break
    end

    run_action(action)
  end
end