I've been wanting an easy way to output usage info for my programs that use
GetoptLong, without having to duplicate all the option information; once
for the creation of the GetoptLong object, and again in a help message.
I've taken a crack at altering GetoptLong to support a "usage" method that
essentially does what I want.
Basically what it does is have you include a fourth parameter for each
option: the description. This is used internally, then removed from each
array, the collection is then passed to the original initialize method for
regular processing. Calling the usage method of your GetoptLong object will
print out a user-defined message (or a default) and then iterates over the
options, printing both long and short versions, and the description. I've
included the code below in a test program. I'm not finished with it, but I
wanted to share it. I want to make the output a little prettier and maybe
make it more flexible. I don't know yet. I welcome any suggestions or
comments.
####
require 'getoptlong'
class GetoptLong
alias old_init initialize
def initialize(*options)
@descriptions = Hash.new
options.each do |arg|
key = arg[0..1]
desc = arg[3]
@descriptions[key] = desc
arg.pop
end
old_init(*options)
end
def usage(message="Usage:")
puts "#{message}"
@descriptions.sort.each do |k, v|
printf "%15s => %-40s\n", k.join(", "), v
end
end
end
opts = GetoptLong.new(["--date", "-d", GetoptLong::REQUIRED_ARGUMENT,
"specify a date"],
["--quiet", "-q", GetoptLong::NO_ARGUMENT, "be verry
quiet"],
["--help", "-h", GetoptLong::NO_ARGUMENT, "Print this
help page"])
opts.each do |opt, arg|
case opt
when "--date"
puts "Date passed"
when "--help"
opts.usage("Usage: goltest [options]\n\n")
# opts.usage
exit
end
end