I've written a working script that has several command line options. I want to make a few of these options required options. My research got me to the following code. You'll see at the end of the script I'm checking separately that the options have been supplied.
In python, the argparse module has an argument "required=True" that would automatically exit the program if the given argument was supplied. I couldn't find anything like that in the ruby module. Is there a different, more advanced argument parsing module? Is there a more concise way to write this code?
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "\nUsage: How to use the code"
opts.on('--debug',
"Change log level to debug. Default is INFO") do |l|
options[:debug] = l
end
options[:logfile] = "stage_refresh.out"
opts.on('-l', '--logfile LOGFILE', "Logfile to log results. Default is stage_refresh.out") do |l|
options[:source] = l
end
options[:source] = "localhost"
opts.on('-s', '--source SOURCE_HOST', "Source host for dump. Default is localhost") do |s|
options[:source] = s
end
opts.on('-t', '--target TARGET', "Target host to refresh. Must specify.") do |t|
options[:target] = t
end
end
optparse.parse!
unless options[:source_pass]
puts "Must have --source_pass PASSWORD"
end
unless options[:target]
puts "Must have --target TARGET_SERVER"
end
if options[:debug]
logger.level = Logger::DEBUG
else
logger.level = Logger::INFO
end
puts options[:source_pass]
puts options[:target]
.................