Ruby,Thor gem ArgumentError

时间:2013-04-10 13:54:15

标签: ruby thor

我正在开发一个应该用作CLI实用程序的Ruby gem。

我决定使用rails命令使用的Thor,并且似乎非常灵活(与rakelink的差异)。

问题是我找不到如何处理输入错误。 例如,如果我键入错误的选项,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

...但它不起作用


新细节:

好的,我注意到该方法是在类上声明的,而不是实例。我尝试了以下操作并且似乎工作得很好,但它并不理想,而且有点hacky:

file: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".

无论如何,还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

如果您查看错误消息:

 Ambiguous command h matches [hello, help]

上述方法,对于h,Thor发现了多个匹配项。这是由于help命令已经定义(内置)。

我建议您使用内置的帮助命令来显示帮助&amp;关于CLI工具的选项。

要使一个字母命令快捷方式正常工作 - 您应该将命令命名为不要从h开始,foobar,{{1 }&amp;等等。

如果你想要从字母yo开始的命令,那就更具体了。