我正在试图弄清楚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
具体来说,它如何知道将desc
和method_options
来电映射到哪种方法?
答案 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”。