ruby 中不带参数的 DSL 块
我正在用 ruby 编写一个简单的 dsl。几周前,我偶然发现了一些博客文章,其中展示了如何将以下代码转换
some_method argument do |book|
book.some_method_on_book
book.some_other_method_on_book :with => argument
end
为更简洁的代码:
some_method argument do
some_method_on_book
some_other_method_on_book :with => argument
end
我不记得如何执行此操作,我不确定缺点,但更简洁的语法很诱人。有人对这种转变有任何线索吗?
I'm writing a simple dsl in ruby. Few weeks ago I stumbled upon some blog post, which show how to transform code like:
some_method argument do |book|
book.some_method_on_book
book.some_other_method_on_book :with => argument
end
into cleaner code:
some_method argument do
some_method_on_book
some_other_method_on_book :with => argument
end
I can't remember how to do this and I'm not sure about downsides but cleaner syntax is tempting. Does anyone have a clue about this transformation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:但是,这省略了书,但不允许您使用该参数。要透明地使用它,您必须以某种方式运输它。我建议在书本上这样做:
UPDATE: However, that omits book but don't let you use the argument. To use it transparently you must transport it someway. I suggest to do it on book itself:
看看这篇文章 http://www.dan -manges.com/blog/ruby-dsls-instance-eval-with-delegation — 对该方法进行了概述(具体说明了其缺点和可能的解决方案),另外还有一些有用的链接供进一步阅读。
基本上,它是关于使用instance_eval 在所需的上下文中执行块。
谈论这种技术的缺点:
Take a look at this article http://www.dan-manges.com/blog/ruby-dsls-instance-eval-with-delegation — there is an overview of the method (specifically stated in the context of its downsides and possible solution to them), plus there're several useful links for further reading.
Basically, it's about using instance_eval to execute the block in the desirable context.
Speaking about downside of this technique:
查看 docile gem。它可以处理所有锋利的边缘,使这对您来说非常容易。
Check out the docile gem. It takes care of all the sharp edges, making this very easy for you.