Class: Samovar::One

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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

#defaultObject

The default value if no argument is provided.



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

def default
  @default
end

#descriptionObject (readonly)

A description of the argument for help output.



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

def description
  @description
end

#keyObject

The name of the attribute to store the value in.



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

def key
  @key
end

#patternObject

A pattern to match valid values.



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

def pattern
  @pattern
end

#requiredObject

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_aObject

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_sObject

Generate a string representation for usage output.



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

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