Rails的concat方法和带有do … end的块不起作用
我刚刚阅读了Rails的concat
方法来清理输出内容的助手http://thepugautomatic.com/2013/06/helpers/ 。
我玩了它,我发现,它对带有花括号的块和带有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
我不知道花括号和做…结束块似乎有不同的含义。 有没有办法使用concat
with do … end 而不用括号括起来(第3个例子)? 否则它在某些情况下似乎没用,例如,当我想在其中连接UL时,其中包含许多LI元素,因此我必须使用多行代码。
它归结为Ruby的范围。 使用concat content_tag :strong do "hello" end
,块将传递给concat
,而不是content_tag
。
玩这个代码,你会看到:
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 {}
引用:Henrik N来自“使用concat和capture来清理自定义Rails助手”( http://thepugautomatic.com/2013/06/helpers/ )