Rails的concat方法和带有do ... end的块不起作用

Jos*_*eim 5 concat ruby-on-rails block

我刚刚阅读了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
Run Code Online (Sandbox Code Playgroud)

我不知道花括号和做...结束块似乎有不同的含义.有没有办法使用concatdo ... end 而不用括号括起来(第3个例子)?否则它在某些情况下似乎没用,例如当我想在其中连接UL时,其中包含许多LI元素,因此我必须使用多行代码.

Jos*_*eim 6

归结为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 {}
Run Code Online (Sandbox Code Playgroud)

引用:Henrik N来自"使用concat和capture来清理自定义Rails助手"(http://thepugautomatic.com/2013/06/helpers/)