ruby 如何生成 OptionParser 需要参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16705368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate OptionParser require arguments
提问by lukemh
The code below works, but I am manually raising argument errors for the required arguments using fetch, when I want to build the required arguments into the native OptionParser sytax for required parameters:
下面的代码有效,但是fetch当我想将所需参数构建到所需参数的本机 OptionParser 语法中时,我正在手动引发所需参数的参数错误:
# 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
采纳答案by Mario Visic
There's a similar question with an answer that may help you: "How do you specify a required switch (not argument) with Ruby OptionParser?"
有一个类似的问题,其答案可能对您有所帮助:“您如何使用 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::MissingArgumentexception that you could raise rather than the ArgumentErroryou're currently throwing.
有一个OptionParser::MissingArgument例外,您可以提出而不是ArgumentError您当前正在抛出的例外。
回答by Per Lundberg
Faced with the same situation, I ended up with an option like this. If not all of my mandatory options are provided, output the user-friendly help text generated by OptionParserbased on my defined options. Feels cleaner than throwing an exception and printing a stack trace to the user.
面对同样的情况,我最终做出了这样的选择。如果没有提供我所有的强制选项,输出OptionParser基于我定义的选项生成的用户友好的帮助文本。感觉比抛出异常并向用户打印堆栈跟踪更干净。
options = {}
option_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{##代码##} --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
end

