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.



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

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.



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

def defaults
  @defaults
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

Class Method Details

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



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

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



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

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



122
123
124
# File 'lib/samovar/options.rb', line 122

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

#parse(input, default) ⇒ Object



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

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



153
154
155
# File 'lib/samovar/options.rb', line 153

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

#usage(rows) ⇒ Object



157
158
159
160
161
# File 'lib/samovar/options.rb', line 157

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