2013-04-10 48 views
2

我正在研究應該用作CLI實用程序的Ruby寶石。Ruby,Thor gem參數錯誤

我已經決定使用Thor,即使用的rails命令,似乎是非常靈活(與rake的差異:link)。

問題是我找不到如何處理輸入錯誤。 例如,如果我在一個錯誤的選項類型,雷神自動返回一個很好的警告:

$ myawesomescript blabla 
Could not find command "blabla". 

但是,如果我用的是解決不了的命令時,事情就變得醜陋。例如,有一個「幫助」默認命令,我已經定義了一個「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 

...但它不工作


新的細節:

OK,我注意到,該方法是在課堂上宣佈,而不是實例。我嘗試以下,似乎很好地工作,但它的效果並不理想,有點哈克:

文件: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". 

無論如何,有沒有更好的方法?

+0

你可以分享完整的Thor腳本嗎? – acw 2013-04-17 16:14:17

+0

mmm ...恐怕它變得相當長,雖然它只是調用其他類的前端邏輯。不過,它並沒有偏離[thor home](http://whatisthor.com/)上的例子。 – tompave 2013-04-17 18:34:56

回答

1

如果你看一下錯誤信息:

Ambiguous command h matches [hello, help] 

以上手段,對h,雷神是找到一個以上的匹配。這是由於help命令已經定義(內置)。

我不建議使用內置幫助命令來顯示有關CLI工具的幫助&選項。

爲了得到一個字母命令的快捷鍵工作 - 您應該爲您的命令不從信h開始,像foobaryo &等等等等。

如果你想要從字母h開始的命令,只是更具體。

+0

謝謝你的建議。是的,這是有道理的,但問題更多的是關於防止ruby回溯顯示在一般情況下,而不僅僅是在這種特定的照顧下。儘管如此,還是爲最近的回答歡呼。 – tompave 2016-11-27 15:34:14