Class: Ace::Support::Cli::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/support/cli/registry.rb

Defined Under Namespace

Classes: NestedRegistry, Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(version: nil) ⇒ Registry

Returns a new instance of Registry.



13
14
15
16
# File 'lib/ace/support/cli/registry.rb', line 13

def initialize(version: nil)
  @version = version
  @root = Node.new(nil, {})
end

Instance Attribute Details

#versionObject (readonly)

Returns the value of attribute version.



11
12
13
# File 'lib/ace/support/cli/registry.rb', line 11

def version
  @version
end

Instance Method Details

#commandsObject



49
50
51
52
53
# File 'lib/ace/support/cli/registry.rb', line 49

def commands
  @root.children.each_with_object({}) do |(name, node), hash|
    hash[name] = node.command || NestedRegistry.new(node)
  end
end

#register(name, command_class = nil) {|NestedRegistry.new(node)| ... } ⇒ Object

Yields:



18
19
20
21
22
23
# File 'lib/ace/support/cli/registry.rb', line 18

def register(name, command_class = nil)
  node = ensure_path(name)
  node.command = command_class if command_class
  yield NestedRegistry.new(node) if block_given?
  self
end

#resolve(args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/ace/support/cli/registry.rb', line 25

def resolve(args)
  raise CommandNotFoundError, "No commands registered" if @root.children.empty?
  raise CommandNotFoundError, "No command provided" if args.empty?

  tokens = args.dup
  node = @root
  consumed = 0

  tokens.each do |token|
    child = node.children[token]
    break unless child

    node = child
    consumed += 1
  end

  unless node.command
    attempted = tokens.first(consumed + 1).join(" ")
    raise CommandNotFoundError, "Command not found: #{attempted.strip}"
  end

  [node.command, tokens.drop(consumed)]
end