Class: CommandTree::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/command_tree/tree.rb

Overview

A tree of commands and associated keys for every node

Instance Method Summary collapse

Constructor Details

#initializeTree

Returns a new instance of Tree.



10
11
12
# File 'lib/command_tree/tree.rb', line 10

def initialize
  @calls = { '' => nil }
end

Instance Method Details

#group(prefix, name, options = {}) {|subtree| ... } ⇒ Object

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

Yields:

  • (subtree)


33
34
35
36
37
38
# 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 = {}) ⇒ Object

merge a subtree with a prefix and a name



47
48
49
50
51
52
53
54
# 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) ⇒ Object

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



18
19
20
21
22
23
24
25
26
27
# 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

#showObject

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



42
43
44
# File 'lib/command_tree/tree.rb', line 42

def show
  execute_path('')
end