2011-04-14 61 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