I\'m writing a script and I want to require a --host
switch with value, but if the --host
switch isn\'t specified, I want the option parsing to fai
I came up with a clear and concise solution that sums up your contributions. It raises an OptionParser::MissingArgument
exception with the missing arguments as a message. This exception is catched in the rescue
block along with the rest of exceptions coming from OptionParser
.
#!/usr/bin/env ruby
require 'optparse'
options = {}
optparse = OptionParser.new do |opts|
opts.on('-h', '--host hostname', "Host name") do |host|
options[:host] = host
end
end
begin
optparse.parse!
mandatory = [:host]
missing = mandatory.select{ |param| options[param].nil? }
raise OptionParser::MissingArgument, missing.join(', ') unless missing.empty?
rescue OptionParser::ParseError => e
puts e
puts optparse
exit
end
Running this example:
./program
missing argument: host
Usage: program [options]
-h, --host hostname Host name