【问题标题】:On Ruby's Thor, How to show the command usage from within the application在 Ruby 的 Thor 上,如何从应用程序中显示命令用法
【发布时间】:2017-09-12 02:01:43
【问题描述】:

我正在使用 Ruby 和 Thor 构建一个 CLI,如果没有通过任何选项,我想在屏幕上打印命令用法。

下面的伪代码行:

Class Test < Thor
  desc 'test', 'test'
  options :run_command

  def run_command
    if options.empty?
      # Print Usage
    end
  end
end

我目前正在使用以下 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

这样做的正确方法是什么?

【问题讨论】:

    标签: ruby thor


    【解决方案1】:

    您可以使用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
    

    然后在没有选项的情况下运行:

    $ ruby example.rb run_command
    Usage:
      example.rb run_command --from=FROM
    
    Options:
      [--from=FROM]
    
    test usage help
    

    并使用选项运行:

    $ ruby example.rb run_command --from=somewhere
    Called command from somewhere
    

    【讨论】:

    • Test.command_help(Thor::Base.shell.new, 'run_command') 就像一个魅力!非常感谢! =))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多