用 Ruby 编写类似 Thor gem 的 DSL?
我试图弄清楚 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
调用映射到哪个方法?
I'm trying to figure out how the Thor gem creates a DSL like this (first example from their 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
Specifically, how does it know which method to map the desc
and method_options
call to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
desc
非常容易实现,诀窍是使用Module.method_added
:任何继承于
DescMethods
的类都会有一个desc
方法如Thor
。对于每种方法,都会打印一条消息,其中包含方法名称和说明。例如:当定义此类时,将打印字符串“test描述为Hello world”。
desc
is pretty easy to implement, the trick is to useModule.method_added
:any class that inherits from
DescMethods
will have adesc
method likeThor
. For each method a message will be printed with the method name and description. For example:when this class is defined the string "test described as Hello world" will be printed.