2

我试图弄清楚Thor gem如何创建这样的 DSL(他们的 README 中的第一个示例)

class App < Thor                                                 # [1]
  map "-L" => :list                                              # [2]

  desc "install APP_NAME", "install one of the available apps"   # [3]
  method_options :force => :boolean, :alias => :string           # [4]
  def install(name)
    user_alias = options[:alias]
    if options.force?
      # do something
    end
    # other code
  end

  desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
  def list(search="")
    # list everything
  end
end

具体来说,它如何知道映射descmethod_options调用哪个方法?

4

1 回答 1

9

desc很容易实现,诀窍是使用Module.method_added

class DescMethods
  def self.desc(m)
    @last_message = m
  end

  def self.method_added(m)
    puts "#{m} described as #{@last_message}"
  end
end

任何继承自的类DescMethods都将具有desc类似Thor. 对于每个方法,将打印一条带有方法名称和描述的消息。例如:

class Test < DescMethods
  desc 'Hello world'
  def test
  end
end

定义此类时,将打印字符串“测试描述为 Hello world”。

于 2010-12-20T14:30:53.243 回答