Ruby中没有参数的DSL块 [英] DSL block without argument in ruby

查看:59
本文介绍了Ruby中没有参数的DSL块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用ruby写一个简单的dsl.几周前,我偶然发现了一些博客文章,其中展示了如何转换代码,例如:

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

输入清洁代码:

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?

推荐答案

def some_method argument, &blk
  #...
  book.instance_eval &blk
  #...
end

更新:但是,这省略了本书,但不允许您使用该参数.要透明地使用它,您必须以某种方式运输它.我建议自己在书上这样做:

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:

class Book
  attr_accessor :argument
end

def some_method argument, &blk
  #...
  book.argument = argument
  book.instance_eval &blk
  #...
end

some_method 'argument' do
   some_method_on_book
   some_other_method_on_book argument
end

这篇关于Ruby中没有参数的DSL块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆