[英]Ruby, Thor gem ArgumentError
我正在研究應該用作CLI實用程序的Ruby gem。
我決定使用rails
命令使用的Thor ,它似乎非常靈活(關於rake
: link的區別)。
問題是我找不到如何處理輸入錯誤。 例如,如果輸入錯誤的選項,Thor會自動返回一個不錯的警告:
$ 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
...但是它不起作用
新細節:
好的,我注意到該方法是在類而不是實例上聲明的。 我嘗試了以下操作,並且看起來運行良好,但這並不理想,而且有點笨拙:
文件: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工具功能的幫助和選項,而不是嘗試繞過它進行修補。
要使一個字母命令快捷方式正常工作 -您應該命名您的命令,不要以字母h
開頭,例如foo
或bar
, yo
等。
如果您要以字母h
開頭的命令,請更具體一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.