Class: Clap

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, opts) ⇒ Clap

Returns a new instance of Clap.



9
10
11
12
# File 'lib/clap.rb', line 9

def initialize(argv, opts)
  @argv = argv.dup
  @opts = opts
end

Instance Attribute Details

#argvObject (readonly)

Returns the value of attribute argv.



2
3
4
# File 'lib/clap.rb', line 2

def argv
  @argv
end

#optsObject (readonly)

Returns the value of attribute opts.



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

def opts
  @opts
end

Class Method Details

.run(args, opts) ⇒ Object



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

def self.run(args, opts)
  new(args, opts).run
end

Instance Method Details

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/clap.rb', line 14

def run
  args = []

  while argv.any?

    item = argv.shift
    flag = opts[item]

    if flag

      # Work around lambda semantics in 1.8.7.
      arity = [flag.arity, 0].max

      # Raise if there are not enough parameters
      # available for the flag.
      if argv.size < arity
        raise ArgumentError
      end

      # Call the lambda with N items from argv,
      # where N is the lambda's arity.
      flag.call(*argv.shift(arity))
    else

      # Collect the items that don't correspond to
      # flags.
      args << item
    end
  end

  args
end