我正在研究應該用作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".
無論如何,有沒有更好的方法?
你可以分享完整的Thor腳本嗎? – acw 2013-04-17 16:14:17
mmm ...恐怕它變得相當長,雖然它只是調用其他類的前端邏輯。不過,它並沒有偏離[thor home](http://whatisthor.com/)上的例子。 – tompave 2013-04-17 18:34:56