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

2024-01-12

我刚刚读到 Rails 的concat清理在这里输出内容的助手的方法http://thepugautomatic.com/2013/06/helpers/ 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

我不知道花括号和 do...end 块似乎有不同的含义。有没有办法使用concat与...结束without在它周围加上括号(第三个例子)?否则,对于某些情况,例如,它似乎毫无用处。当我想将 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/ http://thepugautomatic.com/2013/06/helpers/)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 的 concat 方法和 do...end 块不起作用 的相关文章

随机推荐