Class: DocoptNG::Option

Inherits:
ChildPattern show all
Defined in:
lib/docopt_ng/option.rb

Instance Attribute Summary collapse

Attributes inherited from ChildPattern

#value

Attributes inherited from Pattern

#children

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ChildPattern

#flat, #match

Methods inherited from Pattern

#==, #dump, #either, #fix, #fix_identities, #fix_repeating_arguments, #to_str

Constructor Details

#initialize(short = nil, long = nil, argcount = 0, value = false) ⇒ Option

Returns a new instance of Option.

Raises:

  • (RuntimeError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/docopt_ng/option.rb', line 8

def initialize(short = nil, long = nil, argcount = 0, value = false)
  raise RuntimeError unless [0, 1].include? argcount

  @short = short
  @long = long
  @argcount = argcount
  @value = value

  @value = if (value == false) && argcount.positive?
    nil
  else
    value
  end
end

Instance Attribute Details

#argcountObject

Returns the value of attribute argcount.



6
7
8
# File 'lib/docopt_ng/option.rb', line 6

def argcount
  @argcount
end

#longObject (readonly)

Returns the value of attribute long.



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

def long
  @long
end

#shortObject (readonly)

Returns the value of attribute short.



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

def short
  @short
end

Class Method Details

.parse(option_description) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/docopt_ng/option.rb', line 23

def self.parse(option_description)
  short = nil
  long = nil
  argcount = 0
  value = false
  options, _, description = option_description.strip.partition('  ')

  options = options.tr(',', ' ').tr('=', ' ')

  options.split.each do |s|
    if s.start_with?('--')
      long = s
    elsif s.start_with?('-')
      short = s
    else
      argcount = 1
    end
  end
  if argcount.positive?
    matched = description.scan(/\[default: (.*)\]/i)
    value = matched[0][0] if matched.count.positive?
  end
  new(short, long, argcount, value)
end

Instance Method Details

#inspectObject



59
60
61
# File 'lib/docopt_ng/option.rb', line 59

def inspect
  "Option(#{short}, #{long}, #{argcount}, #{value})"
end

#nameObject



55
56
57
# File 'lib/docopt_ng/option.rb', line 55

def name
  long || short
end

#single_match(left) ⇒ Object



48
49
50
51
52
53
# File 'lib/docopt_ng/option.rb', line 48

def single_match(left)
  left.each_with_index do |p, n|
    return [n, p] if name == p.name
  end
  [nil, nil]
end