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.



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

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.



92
93
94
# File 'lib/samovar/options.rb', line 92

def defaults
  @defaults
end

#keyObject (readonly)

Returns the value of attribute key.



91
92
93
# File 'lib/samovar/options.rb', line 91

def key
  @key
end

Class Method Details

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



71
72
73
74
75
76
77
# File 'lib/samovar/options.rb', line 71

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



98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/samovar/options.rb', line 98

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) ⇒ Object



94
95
96
# File 'lib/samovar/options.rb', line 94

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

#parse(input) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
# File 'lib/samovar/options.rb', line 113

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

#to_sObject



125
126
127
# File 'lib/samovar/options.rb', line 125

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

#usage(rows) ⇒ Object



129
130
131
132
133
# File 'lib/samovar/options.rb', line 129

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