我正在使用 Ruby 和 Thor 构建 CLI,如果没有传递任何选项,我想在屏幕上打印命令用法。
下面的伪代码行中的一些内容:
Class Test < Thor
desc 'test', 'test'
options :run_command
def run_command
if options.empty?
# Print Usage
end
end
end
Run Code Online (Sandbox Code Playgroud)
我目前正在使用以下 hack(我并不为此感到自豪!=P):
Class Test < Thor
desc 'test', 'test'
options :run_command
def run_command
if options.empty?
puts `my_test_command help run_command`
end
end
end
Run Code Online (Sandbox Code Playgroud)
执行此操作的正确方法是什么?
您可以使用command_help以下命令显示帮助信息:
require 'thor'
class Test < Thor
desc 'run_command --from=FROM', 'test usage help'
option :from
def run_command
unless options[:from]
Test.command_help(Thor::Base.shell.new, 'run_command')
return
end
puts "Called command from #{options[:from]}"
end
end
Test.start
Run Code Online (Sandbox Code Playgroud)
然后不带任何选项运行:
$ ruby example.rb run_command
Usage:
example.rb run_command --from=FROM
Options:
[--from=FROM]
test usage help
Run Code Online (Sandbox Code Playgroud)
并使用以下选项运行:
$ ruby example.rb run_command --from=somewhere
Called command from somewhere
Run Code Online (Sandbox Code Playgroud)