Herms
Herms

Reputation: 38798

Set up default option handler for ruby's OptionParser

I'm trying to get simple option handling in my ruby app. Looks like OptionParser does most of what I want, though I can't figure out a way to gracefully handle unexpected arguments.

If any unexpected arguments are provided I want to treat it as if the -h argument was passed (show usage and quit). I'm not seeing any way to handle that though.

If OptionParser can't do it, is there another library I could use for easily parsing command line arguments?

Upvotes: 7

Views: 3521

Answers (2)

ktsujister
ktsujister

Reputation: 501

if you save below as test.rb

#/usr/bin/env ruby
require 'optparse'

test = nil
help = nil
ARGV.options {|opt|
  opt.on("--test=test") {|val| test=val}
  help = opt.help
  begin
    opt.parse!
  rescue OptionParser::InvalidOption => e
    puts help
  end
}

and execute below in the terminal,

$./test.rb --foo

you get below.

Usage: test [options]
    --test=test

Upvotes: 0

Wayne Conrad
Wayne Conrad

Reputation: 108039

There's probably a slick way to do it, but I don't know it. I've done this:

  opts = OptionParser.new
  ...
  opts.on_tail("-h", "--help",
               "Show this message") do
    puts opts
    exit
  end
  begin      
    opts.parse!(argv)
  rescue OptionParser::InvalidOption => e
    puts e
    puts opts
    exit(1)
  end

Upvotes: 10

Related Questions