Class: TTY::MenuTree::Prompt

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

Overview

Thin wrapper around TTY::Prompt that knows how to render a list of actions and, optionally, a "Back" entry.

Menu only depends on the #select_action method, so you may pass any object that implements it if you want fully custom rendering.

Constant Summary collapse

DEFAULT_BACK_LABEL =
"\u21A9\uFE0F  Back"

Instance Method Summary collapse

Constructor Details

#initialize(tty_prompt: TTY::Prompt.new(active_color: :cyan, help_color: :bright_black), back_label: DEFAULT_BACK_LABEL) ⇒ Prompt

Returns a new instance of Prompt.

Parameters:

  • tty_prompt (TTY::Prompt) (defaults to: TTY::Prompt.new(active_color: :cyan, help_color: :bright_black)) —

    the underlying prompt to drive.

  • back_label (String) (defaults to: DEFAULT_BACK_LABEL) —

    label used for the "Back" entry.



17
18
19
20
21
# File 'lib/tty/menu_tree/prompt.rb', line 17

def initialize(tty_prompt: TTY::Prompt.new(active_color: :cyan, help_color: :bright_black),
               back_label: DEFAULT_BACK_LABEL)
  @tty_prompt = tty_prompt
  @back_label = back_label
end

Instance Method Details

#select_action(title, actions, back: false) ⇒ Object?

Present actions and return the one the user picked.

Parameters:

  • title (String) —

    heading shown above the choices.

  • actions (Array<#name>) —

    selectable actions.

  • back (Boolean) (defaults to: false) —

    when true, append a "Back" entry that returns nil when chosen.

Returns:

  • (Object, nil) —

    the selected action, or nil when "Back" was chosen.



31
32
33
34
35
# File 'lib/tty/menu_tree/prompt.rb', line 31

def select_action(title, actions, back: false)
  choices = actions.to_h { |action| [action.name, action] }
  choices[@back_label] = nil if back
  @tty_prompt.select("\n#{title}", choices, per_page: choices.size)
end