使用ruby的OptionParser解析子命令
我希望能够使用 ruby 的 OptionParser 来解析
COMMAND [GLOBAL FLAGS] [SUB-COMMAND [SUB-COMMAND FLAGS]]
以下形式的子命令:
git branch -a
gem list foo
我知道我可以切换到不同的选项解析器库(如 Trollop),但我有兴趣学习如何从内部执行此操作OptionParser,因为我想更好地学习这个库。
有什么建议吗?
I'd like to be able to use ruby's OptionParser to parse sub-commands of the form
COMMAND [GLOBAL FLAGS] [SUB-COMMAND [SUB-COMMAND FLAGS]]
like:
git branch -a
gem list foo
I know I could switch to a different option parser library (like Trollop), but I'm interested in learning how to do this from within OptionParser, since I'd like to learn the library better.
Any tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
想通了。我需要使用 OptionParser#order! 。它将解析从
ARGV
开头开始的所有选项,直到找到非选项(不是选项参数),从ARGV
中删除它处理的所有内容,并且然后它就会退出。所以我只需要做类似的事情:
Figured it out. I need to use
OptionParser#order!
. It will parse all the options from the start ofARGV
until it finds a non-option (that isn't an option argument), removing everything it processes fromARGV
, and then it will quit.So I just need to do something like:
看起来 OptionParser 语法已经改变了一些。我必须使用以下内容,以便参数数组具有 opts 对象未解析的所有选项。
It looks like the OptionParser syntax has changed some. I had to use the following so that the arguments array had all of the options not parsed by the opts object.
GLI 是必经之路,https://github.com/davetron5000/gli。教程摘录:
您可以在 http://davetron5000.github.io/gli/ 找到该教程。
GLI is the way to go, https://github.com/davetron5000/gli. An excerpt from a tutorial:
You can find the tutorial at http://davetron5000.github.io/gli/.
您还可以查看其他一些宝石,例如 main。
There are also other gems you can look at such as main.