在Ruby中编写像Thor gem一样的DSL?

时间:2010-12-20 14:20:31

标签: ruby dsl thor

我正在试图弄清楚Thor gem如何创建这样的DSL(来自自述文件的第一个例子)

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来电映射到哪种方法?

1 个答案:

答案 0 :(得分: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

定义此类时,将打印字符串“test we as Hello world”。