Parse input based on metadata in option_specs.
opt = GetOptions.new(%w(help verbose! strarg=s)) puts "I'm going to go do stuff..." if (opt.verbose) ...
# File lib/getoptions.rb, line 143 def initialize(option_specs, input = ARGV) build_dict(option_specs) @options = {} leftover = [] until input.empty? arg = input.shift case arg # Stop if you hit -- when '--' break # Long form when /^--(\S+)/ o, a = $1.split('=', 2) input.unshift(a) if a input = process_arguments(o, input) # Short form when /^-(\S+)/ o, a = $1.split('=', 2) input.unshift(a) if a o.scan(/./) do |c| input = process_arguments(c, input) end # Not an option, leave it else leftover << arg end end # Put what didn't parse back into input input.concat(leftover) end
Returns the value of the specified option. If the option was in the specification but not found in the input data, nill is returned.
# File lib/getoptions.rb, line 186 def [](k) raise ParseError.new("`nil' cannot be an option key") if (k.nil?) sym = k.to_sym key = k.to_s case when @options.has_key?(sym); @options[sym] when @dict.has_key?(key); (@dict[key].option_type == :increment) ? 0 : nil else raise ParseError.new("program tried to access an unknown option: #{key.inspect}") end end
Iterate over each parsed option name and value.
opt.each do |key,val|
puts "#{key} -> #{val.inspect}"
end
# File lib/getoptions.rb, line 233 def each @options.each do |key,value| yield key.to_s, value end end
Returns true if the specified key exists in the option input.
opt = GetOptions.new(%w(help verbose! strarg=s)) puts "I'm going to go do stuff..." if (opt.has_option(:verbose)) puts "I don't exist..." if (opt.has_option(:bogus)) ...
# File lib/getoptions.rb, line 210 def has_option?(k) raise ParseError.new("`nil' cannot be an option key") if (k.nil?) @options.has_key?(k.to_sym) end
# File lib/getoptions.rb, line 217 def inspect @options.sort_by{|k| k.to_s}.collect do |key, val| "%s: %s" % [key.inspect, val.inspect] end.join($/) end
Generated with the Darkfish Rdoc Generator 2.