Class: Dominion::Parser

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

Constant Summary collapse

COMMAND =
/\w+(?::\w+)*/

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
# File 'lib/dominion.rb', line 13

def initialize(args)
  @args     = args.dup
  @mappers  = []
end

Instance Method Details

#command(matcher, options = {}, &mappers) ⇒ Object



18
19
20
21
22
23
# File 'lib/dominion.rb', line 18

def command(matcher, options = {}, &mappers)
  if @invoker.for?(matcher)
    yield if block_given?
    @invoker.options = options
  end
end

#map(arg, opts) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/dominion.rb', line 25

def map(arg, opts)
  if switch?(arg)
    @mappers.unshift(lambda { extract_option(@args, arg, opts) })
  else
    opts[:to] ||= arg

    @mappers.push(lambda { extract_option(@args, arg, opts) })
  end
end

#parse(&block) ⇒ Object

Raises:



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/dominion.rb', line 35

def parse(&block)
  @invoker = Invoker.new(@args.shift)
  @result  = {}

  instance_eval(&block)

  @mappers.each(&:call)
  
  raise UnknownArguments, "Unknown arguments: #{@args.join(' ')}" unless @args.empty?

  @invoker.invoke(@result)
end