EDIT: Please, please, please read the two requirements listed at the bottom of this post before replying. People keep posting their new gems and li
EasyOptions does not require any option parsing code at all. Just write the help text, require, done.
## Options:
## -i, --interactive Interactive mode
## -q, --quiet Silent mode
require 'easyoptions'
unless EasyOptions.options[:quiet]
puts 'Interactive mode enabled' if EasyOptions.options[:interactive]
EasyOptions.arguments.each { |item| puts "Argument: #{item}" }
end
Here's the standard technique I usually use:
#!/usr/bin/env ruby
def usage(s)
$stderr.puts(s)
$stderr.puts("Usage: #{File.basename($0)}: [-l <logfile] [-q] file ...")
exit(2)
end
$quiet = false
$logfile = nil
loop { case ARGV[0]
when '-q' then ARGV.shift; $quiet = true
when '-l' then ARGV.shift; $logfile = ARGV.shift
when /^-/ then usage("Unknown option: #{ARGV[0].inspect}")
else break
end; }
# Program carries on here.
puts("quiet: #{$quiet} logfile: #{$logfile.inspect} args: #{ARGV.inspect}")
Apparently @WilliamMorgan and I think alike. I just released last night to Github what I now see is a similar library to Trollop (Named how?) after having done a search for OptionParser on Github, see Switches
There are a few differences, but the philosophy is the same. One obvious difference is that Switches is dependent on OptionParser.
Here's my favorite quick-and-dirty option parser:
case ARGV.join
when /-h/
puts "help message"
exit
when /-opt1/
puts "running opt1"
end
The options are regular expressions, so "-h" also would match "--help".
Readable, easy to remember, no external library, and minimal code.
You can try something like:
if( ARGV.include( '-f' ) )
file = ARGV[ARGV.indexof( '-f' ) + 1 )]
ARGV.delete('-f')
ARGV.delete(file)
end
I'm developing my own option parser gem called Acclaim.
I wrote it because I wanted to create git-style command line interfaces and be able to cleanly separate the functionality of each command into separate classes, but it can also be used without the entire command framework as well:
(options = []) << Acclaim::Option.new(:verbose, '-v', '--verbose')
values = Acclaim::Option::Parser.new(ARGV, options).parse!
puts 'Verbose.' if values.verbose?
No stable release as of yet, but I've already implemented some features like:
There's a lot of emphasis on commands so it might be a little heavy for simple command line parsing but it works well and I've been using it on all of my projects. If you're interested in the command interface aspect then check out the project's GitHub page for more information and examples.