Class: Samovar::Options

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title = "Options", key: :options) ⇒ Options

Returns a new instance of Options.



105
106
107
108
109
110
111
112
113
114
115
# File 'lib/samovar/options.rb', line 105

def initialize(title = "Options", key: :options)
	@title = title
	@ordered = []
	
	# We use this flag to option cache to improve parsing performance:
	@keyed = {}
	
	@key = key
	
	@defaults = {}
end

Instance Attribute Details

#defaultsObject (readonly)

Returns the value of attribute defaults.



118
119
120
# File 'lib/samovar/options.rb', line 118

def defaults
  @defaults
end

#keyObject (readonly)

Returns the value of attribute key.



117
118
119
# File 'lib/samovar/options.rb', line 117

def key
  @key
end

Class Method Details

.parse(*args, **options, &block) ⇒ Object



97
98
99
100
101
102
103
# File 'lib/samovar/options.rb', line 97

def self.parse(*args, **options, &block)
	options = self.new(*args, **options)
	
	options.instance_eval(&block) if block_given?
	
	return options
end

Instance Method Details

#<<(option) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/samovar/options.rb', line 124

def << option
	@ordered << option
	option.flags.each do |flag|
		@keyed[flag.prefix] = option
		
		flag.alternatives.each do |alternative|
			@keyed[alternative] = option
		end
	end
	
	if default = option.default
		@defaults[option.key] = option.default
	end
end

#option(*args, **options, &block) ⇒ Object



120
121
122
# File 'lib/samovar/options.rb', line 120

def option(*args, **options, &block)
	self << Option.new(*args, **options, &block)
end

#parse(input, default) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
# File 'lib/samovar/options.rb', line 139

def parse(input, default)
	values = (default || @defaults).dup
	
	while option = @keyed[input.first]
		if result = option.parse(input)
			values[option.key] = result
		end
	end
	
	return values
end

#to_sObject



151
152
153
# File 'lib/samovar/options.rb', line 151

def to_s
	@ordered.collect(&:to_s).join(' ')
end

#usage(rows) ⇒ Object



155
156
157
158
159
# File 'lib/samovar/options.rb', line 155

def usage(rows)
	@ordered.each do |option|
		rows << option
	end
end