我正在研究一个ruby gem,它应该用作CLI实用程序。
我决定使用Thor,这是由rails命令使用的,并且看起来非常灵活(与rake)的差异。
问题是我找不到如何处理输入错误。
例如,如果我输入了错误的选项,thor会自动返回一个很好的警告:

$ myawesomescript blabla
Could not find command "blabla".

但是,如果我使用一个无法解决的命令,事情就会变得很糟糕。例如,有一个“help”默认命令,我定义了一个“hello”命令如果我只输入“h”,这就是我得到的:
$ myawesomescript h
/Users/Tom/.rvm/gems/ruby-2.0.0-p0/gems/thor-0.18.1/lib/thor.rb:424:in `normalize_command_name': Ambiguous command h matches [hello, help] (ArgumentError)
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/gems/thor-0.18.1/lib/thor.rb:340:in `dispatch'
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/gems/thor-0.18.1/lib/thor/base.rb:439:in `start'
    from /Users/Tom/Documents/ruby/myawesomescript/bin/myawesomescript:9:in `<top (required)>'
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/bin/myawesomescript:23:in `load'
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/bin/myawesomescript:23:in `<main>'
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/bin/ruby_noexec_wrapper:14:in `eval'
    from /Users/Tom/.rvm/gems/ruby-2.0.0-p0/bin/ruby_noexec_wrapper:14:in `<main>'
myawesomescript $

现在,我知道只输入“h”是愚蠢的,我可以重命名我的命令,但我不希望用户看到这种错误消息。
我试图用以下方法重写该方法:
def normalize_command_name(meth)
  super(meth)
rescue ArgumentError => e
  puts "print something useful"
end

…但它不起作用
新细节:
好的,我注意到该方法是在类上声明的,而不是在实例上声明的。我尝试了下面的方法,看起来效果不错,但并不理想,而且有点老套:
文件:lib/myawesomescript/thor_overrides.rb
require 'thor'

class Thor
  class << self

    protected
      def normalize_command_name(meth)
        return default_command.to_s.gsub('-', '_') unless meth

        possibilities = find_command_possibilities(meth)
        if possibilities.size > 1
          raise ArgumentError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]"
        elsif possibilities.size < 1
          meth = meth || default_command
        elsif map[meth]
          meth = map[meth]
        else
          meth = possibilities.first
        end

        meth.to_s.gsub('-','_') # treat foo-bar as foo_bar
      rescue ArgumentError => e
        # do nothing
      end
      alias normalize_task_name normalize_command_name
  end
end

我在这里加了几行:
rescue ArgumentError => e
  # do nothing

它能做到这一点,因为似乎在其他地方,某段代码会处理错误消息:
$ myawesomescript h
Could not find command "h".

不管怎样,有更好的办法吗?

最佳答案

如果查看错误消息:

 Ambiguous command h matches [hello, help]

上面的意思是,对于h,thor找到了多个匹配项这是因为已经定义了help命令(内置)。
我建议您使用内置的help命令来显示cli工具的帮助和选项,而不是试图用monkey-patch来绕过它。
要使一个字母的命令快捷方式工作-您应该命名命令,不要从字母h开始,例如foobaryo等等。
如果您希望命令以字母h开头,请更具体一些。

10-13 09:39