Parsing arguments with defaults and flags
I've got a ruby bin with some arguments, namely -s
, -c
and -r
(short for scrape, create and run). Now I'd like to set some defaults to scrape and create ('.'
in both cases), but if I use :default
in trollop, I can't check wherever that argument is set or not.
project --scrape
should be equivalent to
project --scrape .
how to achieve that?
And while at it, how do I make
开发者_C百科project target
to be equivalent with
project --run target
?
You can modify ARGV
before Trollop processes it. Your best bet would probably be to scan the input arguments, apply some basic transformations, and then run Trollop.
For example:
args = ARGV.split
idx = args.index '--scrape'
if idx != nil
if idx < args.length
if args[idx + 1][0..1] == '--'
args=args[0..idx] + ['.'] + args[idx+1..-1]
end
else
if args[idx + 1][0..1] == '--'
args << '.'
end
end
end
This snippet should check for --scrape
with no parameter following it and add in a '.'
in that case. You can do something similar to check for the omitted --run
parameter. When you are done making your modifications, use args.join(' ')
to put the arguments back together into a string. Assign this new string to ARGV
, and then set Trollop loose.
精彩评论