Class: Samovar::Many

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

Overview

Represents multiple positional arguments in a command.

A ‘Many` parser extracts all arguments from the command line until it encounters a stop pattern (typically an option flag).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, description = nil, stop: /^-/, default: nil, required: false) ⇒ Many

Initialize a new multi-argument parser.



18
19
20
21
22
23
24
# File 'lib/samovar/many.rb', line 18

def initialize(key, description = nil, stop: /^-/, default: nil, required: false)
  @key = key
  @description = description
  @stop = stop
  @default = default
  @required = required
end

Instance Attribute Details

#defaultObject

The default value if no arguments are provided.



44
45
46
# File 'lib/samovar/many.rb', line 44

def default
  @default
end

#descriptionObject (readonly)

A description of the arguments for help output.



34
35
36
# File 'lib/samovar/many.rb', line 34

def description
  @description
end

#keyObject

The name of the attribute to store the values in.



29
30
31
# File 'lib/samovar/many.rb', line 29

def key
  @key
end

#requiredObject

Whether at least one argument is required.



49
50
51
# File 'lib/samovar/many.rb', line 49

def required
  @required
end

#stopObject

A pattern that indicates the end of this argument list.



39
40
41
# File 'lib/samovar/many.rb', line 39

def stop
  @stop
end

Instance Method Details

#parse(input, parent = nil, default = nil) ⇒ Object

Parse multiple arguments from the input.



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/samovar/many.rb', line 79

def parse(input, parent = nil, default = nil)
  if @stop and stop_index = input.index{|item| @stop === item}
    input.shift(stop_index)
  elsif input.any?
    input.shift(input.size)
  elsif default ||= @default
    return default
  elsif @required
    raise MissingValueError.new(parent, @key)
  end
end

#to_aObject

Generate an array representation for usage output.



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/samovar/many.rb', line 61

def to_a
  usage = [to_s, @description]
  
  if @default
    usage << "(default: #{@default.inspect})"
  elsif @required
    usage << "(required)"
  end
  
  return usage
end

#to_sObject

Generate a string representation for usage output.



54
55
56
# File 'lib/samovar/many.rb', line 54

def to_s
  "<#{key}...>"
end