Class: Optitron::Parser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



5
6
7
8
9
10
# File 'lib/optitron/parser.rb', line 5

def initialize
  @options = []
  @commands = {}
  @args = []
  @help = Help.new(self)
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



4
5
6
# File 'lib/optitron/parser.rb', line 4

def args
  @args
end

#commandsObject (readonly)

Returns the value of attribute commands.



4
5
6
# File 'lib/optitron/parser.rb', line 4

def commands
  @commands
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/optitron/parser.rb', line 4

def options
  @options
end

#targetObject

Returns the value of attribute target.



3
4
5
# File 'lib/optitron/parser.rb', line 3

def target
  @target
end

Instance Method Details

#helpObject



12
13
14
# File 'lib/optitron/parser.rb', line 12

def help
  @help.generate
end

#parse(args = ARGV) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/optitron/parser.rb', line 16

def parse(args = ARGV)
  tokens = Tokenizer.new(args).tokens
  response = Response.new(self, tokens)
  options = @options 
  args = @args
  if !@commands.empty?
    potential_cmd_toks = tokens.select { |t| t.respond_to?(:val) }
    if cmd_tok = potential_cmd_toks.find { |t| @commands[t.val] }
      tokens.delete(cmd_tok)
      response.command = cmd_tok.val
      options += @commands[cmd_tok.val].options
      args = @commands[cmd_tok.val].args
    else
      potential_cmd_toks.first ?
        response.add_error('an unknown command', potential_cmd_toks.first.val) :
        response.add_error('unknown command')
    end
  end
  parse_options(tokens, options, response)
  parse_args(tokens, args, response)
  response.validate
  response
end

#parse_args(tokens, args, response) ⇒ Object



50
51
52
# File 'lib/optitron/parser.rb', line 50

def parse_args(tokens, args, response)
  args.each { |arg| arg.consume(response, tokens) } if args
end

#parse_options(tokens, options, response) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/optitron/parser.rb', line 40

def parse_options(tokens, options, response)
  options.each do |opt|
    response.params[opt.name] = opt.default if opt.has_default?
    if opt_tok = tokens.find { |tok| opt.match?(tok) }
      opt_tok_index = tokens.index(opt_tok)
      opt.consume(response, tokens)
    end
  end
end