Ruby OptionParser空开关“-"行为 [英] Ruby OptionParser empty switch "-" behavior

查看:113
本文介绍了Ruby OptionParser空开关“-"行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了使用OptionParser优雅地处理命令行输入的代码.我正面临两个重大打击.

I've wrote code that uses OptionParser to handle command line input gracefully. I am facing two major hits.

  1. 传递一个空的开关'-'不会给出错误.当然,有些程序认为它是有效的,但我的不应该.
  2. 该程序需要两个强制开关,但可以接受一个开关而不会抱怨!例如program.ruby -f foo -b bar是有效输入,并且两个开关均为:REQUIRED.但是只提供一个开关就可以顺利通过,这不是理想的行为.
  1. Passing an empty switches '-' doesn't give an error. Of course some programs take that as valid, but mine shouldn't.
  2. The program requires two mandatory switches, but it accepts one switch without complaining! e.g. program.ruby -f foo -b bar is the valid input and both switches are :REQUIRED. But providing only one switch passes without problem and this is not the desired behavior.

在第一种情况下,我这样做是

For the first case I've done this:

opts.on('-', /\A-\Z/) do
  $stderr.print "Invalid empty switch"
  exit 1
end

工作正常.但这是正确的方法吗?

It works fine. But is this the proper way of doing it?

对于第二种情况,我在OptionParser.new块中四处寻找解决方案,但找不到.例如

For the second case, I've looked around for a solution within the OptionParser.new block but I couldn't find one. e.g.

unless options.foo && options.bar
  puts "Error."
  exit 2
end

在OptionParser.new块之外执行此操作是正常方法吗?

Doing it outside the OptionParser.new block is the normal way?

推荐答案

如果使用的是OptionParser,则需要,显式地禁止空开关并手动检查所需的参数.

If you are using OptionParser, then yes, you need to explicitly disallow the empty switch and manually check the required parameters.

但是,如果您使用其他工具来进行选项解析,例如 defunkt的宝石选择,则可以标记选项和无效选项(例如空开关)将导致打印帮助并退出应用程序.我了解在某些情况下使用OptionParser更有意义,但我个人更喜欢使用更方便工具.

However, if you used another tool for option parsing, such as defunkt's gem choice, you could mark options as required and the invalid options (such as the empty switch) would cause the help to be printed and application to exit. I understand that in some cases it makes more sense to use OptionParser, but personally I prefer to use the more convenient tools out there.

尽管使要求的选项很容易实现,但我还是建议您仔细考虑一下API的决定.您知道多少个命令行实用程序具有必需的选项?将命令行通常分为选项和参数是有原因的,前者通常是可选的,而后者通常是必需的.我会遵守那个既定的惯例.

Even though making options required is pretty easy one way or the other, I would recommend that you think your API decision through. How many command line utilities do you know, that have required options? There's a reason why command line is usually separated into options and arguments, with the former being usually optional and the latter usually required. I would stick to that established convention.

这篇关于Ruby OptionParser空开关“-"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆