我正在学习使用Ruby的OptionParser类。如何提高解析器错误消息的质量?以下是一个带有强制选项的标志示例,该选项必须是hour、day、week或month之一。
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] username"
times = [:hour, :day, :week, :month]
opts.on('-t', '--time=TIME', times,
'Show messages from the last TIME (defaults to weeks)', "Avaliable options are (#{times.join(', ')})") do |time|
o.time = time
end
end以下是一些示例输出。
$ ./script -t
./scraper.rb:195:in `main': missing argument: -t (OptionParser::MissingArgument)
from ./scraper.rb:210:in `<main>'
$ ./script -t not_a_value
./scraper.rb:195:in `main': invalid argument: -t not_a_value (OptionParser::InvalidArgument)
from ./scraper.rb:210:in `<main>'我希望错误中提到可接受的值,比如invalid option for -t 'not_a_value', valid options are hour, day, week, month
发布于 2018-05-01 21:03:46
我用下面的方法来做:
begin
parser.parse! ARGV
rescue OptionParser::InvalidArgument => e
# puts e.instance_variables
# puts e.args
# puts e.reason
if e.args.include? '-t'
STDERR.puts "Invalid value of parameter -t. Availible options: #{t_options}"
puts parser.help
exit 1
end
STDERR.puts e
end如果参数-t缺失,则打印输出紧随其后。否则,打印默认错误消息。留下了一些注释掉的“out”行,我可以帮助你在异常数据中找到更多有用的东西。
发布于 2014-08-22 23:42:58
OptionParser在这方面对你帮助不大,但你可以自己实现它,不会有太多麻烦,而且仍然是枯燥的。只需自己检查正确性,并在需要时抛出错误。
times = [:hour, :day, :week, :month]
opts.on('-t', '--time=TIME',
'Show messages from the last TIME (defaults to weeks)',
"Available options are <#{times.join ', '}>") do |time|
times.include?(time.to_sym) or
raise OptionParser::ParseError.new("time must be one of <#{times.join ', '}>")
o.time = time
end让输出更干净一点也很好:
begin
p.parse!(ARGV)
rescue OptionParser::ParseError => e
puts e
exit 1
end发布于 2014-01-31 04:21:04
当然,这就像这样简单:
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] username"
times = [:hour, :day, :week, :month]
begin
opts.on('-t', '--time=TIME', times,
'Show messages from the last TIME (defaults to weeks)', "Avaliable options are (# {times.join(', ')})") do |time|
o.time = time
rescue OptionParser::MissingArgument, OptionParser::InvalidArgument
$stderr.print "Usage: -t <argument> where argument in [:hour, :day, :week, :month]"
end
end
endhttps://stackoverflow.com/questions/21466551
复制相似问题