如何在我的 Ruby Thor 命令行界面应用程序中添加一个--version
选项。
例如,我想要能够运行:
$ thor_app --version
> thor_app version 1.0.0
该问题涉及如何在没有参数或任务名称的情况下运行CLI Thor应用程序,但特别是添加一个不需要任务的--version
选项。
注意
本文采用自我回答格式。鼓励增加其他答案和更新内容。
如何在我的 Ruby Thor 命令行界面应用程序中添加一个--version
选项。
例如,我想要能够运行:
$ thor_app --version
> thor_app version 1.0.0
该问题涉及如何在没有参数或任务名称的情况下运行CLI Thor应用程序,但特别是添加一个不需要任务的--version
选项。
注意
本文采用自我回答格式。鼓励增加其他答案和更新内容。
我用这种方法有些幸运:
class CLI < Thor
map %w[--version -v] => :__print_version
desc "--version, -v", "print the version"
def __print_version
puts FooBar::VERSION
end
end
前导下划线确保没有像yourapp version
这样的命令,强制使用yourapp --version
或yourapp -v
。 desc
内容将允许显示为-v, --version
,而不会暴露__print_version
。
version
列为命令,将--version
和--no-version
列为全局选项,如果该脚本没有任何选项运行,则没有帮助信息输出。最好的方法是在Thor之外进行处理:class CLI < Thor
.
.
.
end
if ARGV[0] == "--version"
puts "MyApp #{MyApp::VERSION}"
exit
end
CLI.start
这个方法的小缺陷在于 --version
没有被记录在文档中。
-v
详细模式,因为所有任务都可以使用它来确定输出信息的详细程度。class CLI < Thor
#include Thor::Actions
class_option :version, :type => :boolean
desc "version", "Show thor_app version"
def version
if options[:version]
puts "thor_app version #{find_version}"
end
end
default_task :version
no_tasks do
def find_version
## Method can be replaced to look up VERSION
'1.0.0'
end
end
end
bundler version
命令来调用它(因为为什么不能呢?) https://github.com/bundler/bundler/blob/6afa89217cf052c58316da1f2be7bf54749ff9de/lib/bundler/cli.rb#L312-L316 - ZombieDevbundle exec bin/gem_name
。 - konyak