我想弄清楚Thor宝石是如何创建这样的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
Run Code Online (Sandbox Code Playgroud)
具体来说,它如何知道映射desc和method_options调用哪种方法?
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
Run Code Online (Sandbox Code Playgroud)
任何继承的类DescMethods都会有desc类似的方法Thor.对于每种方法,将使用方法名称和描述打印消息.例如:
class Test < DescMethods
desc 'Hello world'
def test
end
end
Run Code Online (Sandbox Code Playgroud)
当定义此类时,将打印字符串"test describe as Hello world".
| 归档时间: |
|
| 查看次数: |
662 次 |
| 最近记录: |