class CommandTree::Tree

A tree of commands and associated keys for every node

Attributes

calls[RW]

Public Class Methods

new() click to toggle source
# File lib/command_tree/tree.rb, line 10
def initialize
  @calls = { '' => nil }
end

Public Instance Methods

group(prefix, name, options = {}) { |subtree| ... } click to toggle source

define a group of commands (subtree) the method will create a subtree and pass it to the given block of code if you passed a block otherwise it works in a similar way to register

# File lib/command_tree/tree.rb, line 33
def group(prefix, name, options = {})
  subtree = self.class.new
  yield(subtree) if block_given?

  merge(subtree, prefix, name, options)
end
merge(subtree, prefix, name, options = {}) click to toggle source

merge a subtree with a prefix and a name

# File lib/command_tree/tree.rb, line 47
def merge(subtree, prefix, name, options = {})
  register(prefix, name, options)
  subtree.calls.each do |key, command|
    next unless command

    calls["#{prefix}#{key}"] = command
  end
end
register(path, name, options = {}, &block) click to toggle source

register a `path` to a `name` with a block of code if you wish it to be a command, the following `options` are supported: desc: a description of the item, as a help text for the user

# File lib/command_tree/tree.rb, line 18
def register(path, name, options = {}, &block)
  path = path.to_s
  name = name.to_s
  prefix = path[-1]

  insure_path(path, name, options)
  return unless block_given?

  calls[path] = Command.new(prefix, name, options, &block)
end
show() click to toggle source

Start the tree, prints the first level and walk the user through the tree with keystroks

# File lib/command_tree/tree.rb, line 42
def show
  execute_path('')
end

Private Instance Methods

execute_path(path) click to toggle source
# File lib/command_tree/tree.rb, line 69
def execute_path(path)
  return puts "#{path} couldn't be found..." unless calls.key?(path)

  node = calls[path]
  node.execute if node

  children = get_children(path)
  return if children.empty?

  print_children(children)
  choice = STDIN.getch
  execute_path(path + choice)
end
get_children(path) click to toggle source
# File lib/command_tree/tree.rb, line 83
def get_children(path)
  calls.keys.select do |key|
    key.start_with?(path) && key.length == (path.length + 1)
  end.sort
end
insure_path(path, name, options = {}) click to toggle source
# File lib/command_tree/tree.rb, line 62
def insure_path(path, name, options = {})
  return if path.empty?

  insure_path(path[0...-1], name, options)
  calls[path] = Group.new(path[-1], name, options) unless calls[path]
end
print_children(children) click to toggle source