如何在Thor命令中添加--help,-h标志?

时间:2018-03-01 04:22:53

标签: ruby thor

我在Ruby可执行文件中创建了一个Thor类,并在使用./foo help bar时正确显示了帮助。

为了使其更直观(为了我的用户的理智),我还要支持./foo bar --help./foo bar -h。当我这样做时,我得到:

ERROR: "foo bar" was called with arguments ["--help"]
Usage: "foo bar"

我可以手动执行method_option :help, ...并在bar方法中处理它,但我希望有更简单的方法(将该命令重定向到./foo help bar)。

有谁知道一种简单易行的方法吗?

4 个答案:

答案 0 :(得分:2)

您可以使用class_option来实现此目的。如果设置了一个类选项,则此选项可用于cli中的每个方法,您可以检查它是否已设置,然后调用help方法。

这样的事情:

class CLI < Thor
  class_option :help, type: :boolean

  desc "foo PARAM", "foo"
  def foo(param)
    handle_help_option(:foo)
    # your logic
  end

  def handle_help_option(method_name)
    help(method_name) if options[:help]
  end
end

答案 1 :(得分:1)

假设Foo是继承自Thor的类,您可以在Foo.start之前的某个地方调用以下内容:

help_commands = Thor::HELP_MAPPINGS + ["help"]
# => ["-h", "-?", "--help", "-D"]

if help_commands.any? { |cmd| ARGV.include? cmd }
  help_commands.each do |cmd|
    if match = ARGV.delete(cmd)
      ARGV.unshift match
    end
  end
end

通过将任何帮助命令移动到列表的前面,而不是进入Thor并修补某些方法以获得不同的ARGV解析行为。

答案 2 :(得分:1)

以列出的@ max-pleaner为基础。这还将支持子命令:

man git

答案 3 :(得分:1)

为补充max pleaner的回答,以下内容处理子命令,因为如果将技巧应用到子命令,则帮助会中断。

此外,我选择重载Thor启动命令。

def self.start(*args)
  if (Thor::HELP_MAPPINGS & ARGV).any? and subcommands.grep(/^#{ARGV[0]}/).empty?
    Thor::HELP_MAPPINGS.each do |cmd|
      if match = ARGV.delete(cmd)
        ARGV.unshift match
      end
    end
  end
  super
end