Class: Samovar::One
- Inherits:
-
Object
- Object
- Samovar::One
- Defined in:
- lib/samovar/one.rb
Overview
Represents a single positional argument in a command.
A ‘One` parser extracts exactly one argument from the command line that matches the specified pattern.
Instance Attribute Summary collapse
-
#default ⇒ Object
The default value if no argument is provided.
-
#description ⇒ Object
readonly
A description of the argument for help output.
-
#key ⇒ Object
The name of the attribute to store the value in.
-
#pattern ⇒ Object
A pattern to match valid values.
-
#required ⇒ Object
Whether the argument is required.
Instance Method Summary collapse
-
#initialize(key, description, pattern: //, default: nil, required: false) ⇒ One
constructor
Initialize a new positional argument parser.
-
#parse(input, parent = nil, default = nil) ⇒ Object
Parse a single argument from the input.
-
#to_a ⇒ Object
Generate an array representation for usage output.
-
#to_s ⇒ Object
Generate a string representation for usage output.
Constructor Details
#initialize(key, description, pattern: //, default: nil, required: false) ⇒ One
Initialize a new positional argument parser.
18 19 20 21 22 23 24 |
# File 'lib/samovar/one.rb', line 18 def initialize(key, description, pattern: //, default: nil, required: false) @key = key @description = description @pattern = pattern @default = default @required = required end |
Instance Attribute Details
#default ⇒ Object
The default value if no argument is provided.
44 45 46 |
# File 'lib/samovar/one.rb', line 44 def default @default end |
#description ⇒ Object (readonly)
A description of the argument for help output.
34 35 36 |
# File 'lib/samovar/one.rb', line 34 def description @description end |
#key ⇒ Object
The name of the attribute to store the value in.
29 30 31 |
# File 'lib/samovar/one.rb', line 29 def key @key end |
#pattern ⇒ Object
A pattern to match valid values.
39 40 41 |
# File 'lib/samovar/one.rb', line 39 def pattern @pattern end |
#required ⇒ Object
Whether the argument is required.
49 50 51 |
# File 'lib/samovar/one.rb', line 49 def required @required end |
Instance Method Details
#parse(input, parent = nil, default = nil) ⇒ Object
Parse a single argument from the input.
79 80 81 82 83 84 85 86 87 |
# File 'lib/samovar/one.rb', line 79 def parse(input, parent = nil, default = nil) if input.first =~ @pattern input.shift elsif default ||= @default return default elsif @required raise MissingValueError.new(parent, @key) end end |
#to_a ⇒ Object
Generate an array representation for usage output.
61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/samovar/one.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_s ⇒ Object
Generate a string representation for usage output.
54 55 56 |
# File 'lib/samovar/one.rb', line 54 def to_s "<#{@key}>" end |