Rails的concat方法和块与do...结束不起作用



我刚刚读到了 Rails concat清理在这里输出 http://thepugautomatic.com/2013/06/helpers/内容的帮助程序的方法。

玩弄了它,我发现,它对带有大括号的块和带有 do 的块的反应不同......结束。

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与do一起使用...结尾加括号(第 3 个示例)?否则,在某些情况下它似乎毫无用处,例如,当我想连接一个包含许多 LI 元素的 UL 时,所以我必须使用多行代码。

这归结为 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/)

最新更新