2011-04-14 47 views
16

在命令行中調用thor命令時,這些方法按其模塊/類結構(例如,在獨立的ruby可執行文件中命名空間thor命令

class App < Thor 
    desc 'hello', 'prints hello' 
    def hello 
    puts 'hello' 
    end 
end 

將與命令

thor app:hello 

然而運行,如果進行自我可執行通過把

App.start 

在底部,你可以運行像命令:

app hello 

有沒有辦法n amespace這些命令?所以,你可以調用,例如

app say:hello 
app say:goodbye 

回答

23

另一種方法是使用寄存器:

class CLI < Thor 
    register(SubTask, 'sub', 'sub <command>', 'Description.') 
end 

class SubTask < Thor 
    desc "bar", "..." 
    def bar() 
    # ... 
    end 
end 

CLI.start 

現在 - 假設你的可執行文件名爲foo - 您可以撥打:

$ foo sub bar 

在當前版本的雷神(0.15.0.rc2)有雖然是錯誤,這會導致幫助文本跳過的命名空間子命令:

$ foo sub 
Tasks: 
    foo help [COMMAND] # Describe subcommands or one specific subcommand 
    foo bar    # 

您可以通過覆蓋self.banner並顯式設置命名空間來修復該問題。

class SubTask < Thor 
    namespace :sub 

    def bar ... 

    def self.banner(task, namespace = true, subcommand = false) 
    "#{basename} #{task.formatted_usage(self, true, subcommand)}" 
    end 
end 

formatted_usage的第二個參數是與原始橫幅實現的唯一區別。您也可以這樣做一次,並讓其他子命令thor類從SubTask繼承。現在你得到:

$ foo sub 
Tasks: 
    foo sub help [COMMAND] # Describe subcommands or one specific subcommand 
    foo sub bar    # 

希望有所幫助。

+1

聖潔的廢話!你以前8個小時在哪裏?感謝您的優雅解決方案。 – elmt 2011-12-23 08:16:29

+0

這並不適用於我(0.18.1版),但在https://github.com/wycats/thor/issues/261#issuecomment-16880836上所描述的類似工作確實奏效 – 2013-05-09 18:44:53

5

這是應用程序的一種方式作爲默認的命名空間(相當哈克雖然):

#!/usr/bin/env ruby 
require "rubygems" 
require "thor" 

class Say < Thor 
    # ./app say:hello 
    desc 'hello', 'prints hello' 
    def hello 
    puts 'hello' 
    end 
end 

class App < Thor 
    # ./app nothing 
    desc 'nothing', 'does nothing' 
    def nothing 
    puts 'doing nothing' 
    end 
end 

begin 
    parts = ARGV[0].split(':') 
    namespace = Kernel.const_get(parts[0].capitalize) 
    parts.shift 
    ARGV[0] = parts.join 
    namespace.start 
rescue 
    App.start 
end 

或者,也並不理想:

define_method 'say:hello' 
+0

所以沒有乾淨的方式來做到這一點?它只是不被支持? – rubiii 2011-05-11 10:10:47

+0

我無法確定。我試圖找到一個乾淨的方式,失敗了。我認爲命名空間方法只適用於使用thor命令而不是獨立可執行文件。 – 2011-05-11 14:08:19