Ruby Thor基于名称空间的可执行文件

Sie*_*bbe 5 ruby executable namespaces thor

是否有可能创建一个接受命名空间的基于Thor的Ruby可执行文件?例如,允许命令行中的以下内容:./thorfile greet:formal

鉴于我有以下thorfile:

#!/usr/bin/env ruby

require 'rubygems'
require 'thor'

class TalkTasks < Thor
  namespace       "talk"

  desc      "greet", "says hello"
  def greet
    puts "Hello!"
  end

  class Formal < Thor
    namespace "talk:formal"

    desc    "greet", "says a formal hello"
    def greet
      puts "Good evening!"
    end
  end

end

TalkTasks.start
Run Code Online (Sandbox Code Playgroud)

这个thorfile提供以下任务(thor -T):

thor talk:formal:greet  # says a formal hello
thor talk:greet         # says hello
Run Code Online (Sandbox Code Playgroud)

我也可以直接使用thorfile作为可执行文件:

./thorfile greet
Run Code Online (Sandbox Code Playgroud)

哪个显示:

你好!

我如何获得./thorfile formal:greet(或类似的)在Formal类中执行greet方法,以便显示:

晚上好!

Har*_*ina 0

Formal更改类的命名空间

class Formal < Thor
    namespace "formal"
    ...
end
Run Code Online (Sandbox Code Playgroud)

您已经嵌套了类,因此命名空间也嵌套了。如果你把它们分开,你就可以做talk:formal嘿嘿,没有时间测试它。应该管用。