Class: Cl::Parser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts, args) ⇒ Parser

Returns a new instance of Parser.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/cl/parser.rb', line 7

def initialize(opts, args)
  @opts = {}

  super do
    opts.each do |opt|
      on(*dasherize(opt.strs)) do |value|
        set(opt, value)
      end

      opt.aliases.each do |name|
        on(aliased(opt, name)) do |value|
          @opts[name] = set(opt, value)
        end
      end
    end
  end

  dasherize!(args)
  parse!(args)
end

Instance Attribute Details

#optsObject (readonly)

Returns the value of attribute opts.



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

def opts
  @opts
end

Instance Method Details

#aliased(opt, name) ⇒ Object



28
29
30
31
# File 'lib/cl/parser.rb', line 28

def aliased(opt, name)
  str = opt.strs.detect { |str| str.start_with?('--') } || raise
  str.sub(opt.name.to_s, name.to_s)
end

#dasherize(strs) ⇒ Object



40
41
42
# File 'lib/cl/parser.rb', line 40

def dasherize(strs)
  strs.map { |str| str.gsub('_', '-') if str.start_with?('--') }
end

#dasherize!(strs) ⇒ Object



44
45
46
# File 'lib/cl/parser.rb', line 44

def dasherize!(strs)
  strs.replace(dasherize(strs))
end

#set(opt, value) ⇒ Object

should consider negative arities (e.g. |one, *two|)



34
35
36
37
38
# File 'lib/cl/parser.rb', line 34

def set(opt, value)
  args = [opts, opt.type, opt.name, value]
  args = args[-opt.block.arity, opt.block.arity]
  instance_exec(*args, &opt.block)
end