Class: Slop::Parser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, **config) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
# File 'lib/slop/parser.rb', line 13

def initialize(options, **config)
  @options = options
  @config  = config
  reset
end

Instance Attribute Details

#argumentsObject (readonly)

Returns an Array of String arguments that were not parsed.



11
12
13
# File 'lib/slop/parser.rb', line 11

def arguments
  @arguments
end

#configObject (readonly)

A Hash of configuration options.



8
9
10
# File 'lib/slop/parser.rb', line 8

def config
  @config
end

#optionsObject (readonly)

Our Options instance.



5
6
7
# File 'lib/slop/parser.rb', line 5

def options
  @options
end

Instance Method Details

#parse(strings) ⇒ Object

Traverse ‘strings` and process options one by one. Anything after `–` is ignored. If a flag includes a equals (=) it will be split so that `flag, argument = s.split(’=‘)`.

The ‘call` method will be executed immediately for each option found. Once all options have been executed, any found options will have the `finish` method called on them.

Returns a Slop::Result.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/slop/parser.rb', line 36

def parse(strings)
  reset # reset before every parse

  pairs = strings.each_cons(2).to_a
  # this ensures we still support the last string being a flag,
  # otherwise it'll only be used as an argument.
  pairs << [strings.last, nil]

  @arguments = strings.dup

  pairs.each do |flag, arg|
    break if !flag

    # ignore everything after '--', flag or not
    if flag == '--'
      arguments.delete(flag)
      break
    end

    # support `foo=bar`
    if flag.include?("=")
      flag, arg = flag.split("=")
    end

    if opt = try_process(flag, arg)
      # since the option was parsed, we remove it from our
      # arguments (plus the arg if necessary)
      arguments.delete(flag)
      arguments.delete(arg) if opt.expects_argument?
    end
  end

  Result.new(self).tap do |result|
    used_options.each { |o| o.finish(result) }
  end
end

#resetObject

Reset the parser, useful to use the same instance to parse a second time without duplicating state.



21
22
23
24
25
# File 'lib/slop/parser.rb', line 21

def reset
  @arguments = []
  @options.each(&:reset)
  self
end

#unused_optionsObject

Returns an Array of Option instances that were not used.



79
80
81
# File 'lib/slop/parser.rb', line 79

def unused_options
  options.to_a - used_options
end

#used_optionsObject

Returns an Array of Option instances that were used.



74
75
76
# File 'lib/slop/parser.rb', line 74

def used_options
  options.select { |o| o.count > 0 }
end