下面的代码可以工作,但当我想要将所需参数构建到本机OptionParser系统中以获取所需参数时,我会使用fetch手动引发所需参数的参数错误:
# ocra script.rb -- --type=value
options = {}
OptionParser.new 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
end
opts.on("--company [TYPE]",String, [:jaxon, :doric], "Select Company (jaxon, doric)") do |t|
options["company"] = t
end
end.parse!
opts = {}
opts['type'] = options.fetch('type') do
raise ArgumentError,"no 'type' option specified as a parameter (gl or time)"
end
opts['company'] = options.fetch('company') do
raise ArgumentError,"no 'company' option specified as a parameter (doric or jaxon)"
end发布于 2013-05-23 21:07:39
还有一个类似的问题,它的答案可能会对你有所帮助:"How do you specify a required switch (not argument) with Ruby OptionParser?“
简而言之:似乎没有一种方法可以让选项成为必需的(它们毕竟被称为选项)。
您可以引发一个OptionParser::MissingArgument异常,而不是您当前抛出的ArgumentError。
发布于 2020-02-20 18:49:40
面对同样的情况,我最终做出了这样的选择。如果未提供所有必需选项,则根据我定义的选项输出由OptionParser生成的用户友好的帮助文本。感觉比抛出异常并打印堆栈跟踪给用户更干净。
options = {}
option_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} --data-dir DATA_DIR [options]"
# A non-mandatory option
opts.on('-p', '--port PORT', Integer, 'Override port number') do |v|
options[:port] = v
end
# My mandatory option
opts.on('-d', '--data-dir DATA_DIR', '[Mandatory] Specify the path to the data dir.') do |d|
options[:data_dir] = d
end
end
option_parser.parse!
if options[:data_dir].nil?
puts option_parser.help
exit 1
endhttps://stackoverflow.com/questions/16705368
复制相似问题