lukemh lukemh - 1 year ago 108
Ruby Question

How to generate OptionParser require arguments

The code below works, but I am manually raising argument errors for the required arguments using

, when I want to build the required arguments into the native OptionParser sytax for required parameters:

# ocra script.rb -- --type=value
options = {} do |opts|
opts.banner = "Usage: example.rb [options]"

opts.on("--type [TYPE]",String, [:gl, :time], "Select Exception file type (gl, time)") do |t|
options["type"] = t

opts.on("--company [TYPE]",String, [:jaxon, :doric], "Select Company (jaxon, doric)") do |t|
options["company"] = t


opts = {}
opts['type'] = options.fetch('type') do
raise ArgumentError,"no 'type' option specified as a parameter (gl or time)"

opts['company'] = options.fetch('company') do
raise ArgumentError,"no 'company' option specified as a parameter (doric or jaxon)"

Answer Source

There's a similar question with an answer that may help you: "How do you specify a required switch (not argument) with Ruby OptionParser?"

In short: there doesn't seem to be a way to make an option required (they are called options after all).

There is an OptionParser::MissingArgument exception that you could raise rather than the ArgumentError you're currently throwing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download