Rails的concat方法和带有do ... end的块不起作用 [英] Rails' concat method and blocks with do...end doesn't work

查看:67
本文介绍了Rails的concat方法和带有do ... end的块不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解了Rails的concat方法,以清理在此处输出内容的帮助程序 http://thepugautomatic.com/2013/06/helpers/.

I just read about Rails' concat method to clean up helpers that output something here http://thepugautomatic.com/2013/06/helpers/.

我玩了一下,发现,它对带有花括号的块和带有do ... end的块的反应不同.

I played around with it, and I have found out, that it doesn't react the same way to blocks with curly braces and to blocks with do...end.

def output_something
  concat content_tag :strong { "hello" } # works
  concat content_tag :strong do "hello" end # doesn't work
  concat(content_tag :strong do "hello" end) # works, but doesn't make much sense to use with multi line blocks
end

我不知道花括号和do ... end块似乎有不同的含义.有没有一种方法可以将concat与do ... end 一起使用(第三个示例)?否则,在某些情况下,例如,看起来似乎毫无用处.当我想连接其中包含许多LI元素的UL时,必须使用多行代码.

I didn't know that curly braces and do...end blocks seem to have different meanings. Is there a way to use concat with do...end without putting parenthesis around it (3rd example)? Otherwise it seems to be pretty useless for certain situations, e.g. when I want to concat an UL with many LI elements in it, so I have to use more than one line of code.

推荐答案

这取决于Ruby的作用域.对于concat content_tag :strong do "hello" end,该块将传递给concat,而不是content_tag.

It comes down to Ruby's scoping. With concat content_tag :strong do "hello" end, the block is passed to concat, not to content_tag.

玩弄这段代码,您会看到:

Toy around with this code and you'll see:

def concat(x)
  puts "concat #{x}"
  puts "concat got block!" if block_given?
end

def content_tag(name)
  puts "content_tag #{name}"
  puts "content_tag got block!" if block_given?
  "return value of content_tag"
end

concat content_tag :strong do end
concat content_tag :strong {}

引用:使用concat并捕获以清理自定义Rails助手"的Henrik N( http://thepugautomatic.com/2013/06/helpers/)

Quote: Henrik N from "Using concat and capture to clean up custom Rails helpers" (http://thepugautomatic.com/2013/06/helpers/)

这篇关于Rails的concat方法和带有do ... end的块不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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