Class: DocoptNG::ChildPattern

Inherits:
Pattern
  • Object
show all
Defined in:
lib/docopt_ng/child_pattern.rb

Direct Known Subclasses

Argument, Option

Instance Attribute Summary collapse

Attributes inherited from Pattern

#children

Instance Method Summary collapse

Methods inherited from Pattern

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

Constructor Details

#initialize(name, value = nil) ⇒ ChildPattern

Returns a new instance of ChildPattern.



7
8
9
10
# File 'lib/docopt_ng/child_pattern.rb', line 7

def initialize(name, value = nil)
  @name = name
  @value = value
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



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

def name
  @name
end

#valueObject

Returns the value of attribute value.



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

def value
  @value
end

Instance Method Details

#flat(*types) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/docopt_ng/child_pattern.rb', line 16

def flat(*types)
  if types.empty? || types.include?(self.class)
    [self]
  else
    []
  end
end

#inspectObject



12
13
14
# File 'lib/docopt_ng/child_pattern.rb', line 12

def inspect
  "#{self.class.name}(#{name}, #{value})"
end

#match(left, collected = nil) ⇒ Object



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

def match(left, collected = nil)
  collected ||= []
  pos, match = single_match(left)

  return [false, left, collected] if match.nil?

  left_ = left.dup
  left_.slice!(pos)

  same_name = collected.select { |a| a.name == name }
  if @value.is_a?(Array) || @value.is_a?(Integer)
    increment = if @value.is_a? Integer
      1
    else
      match.value.is_a?(String) ? [match.value] : match.value
    end
    if same_name.count.zero?
      match.value = increment
      return [true, left_, collected + [match]]
    end
    same_name[0].value += increment
    return [true, left_, collected]
  end

  [true, left_, collected + [match]]
end