我刚刚读过Rails的concat
方法,以清理在http://thepugautomatic.com/2013/06/helpers/输出一些东西的助手。
我玩了一下,然后发现,它对带有花括号的块和带有do ... end的块的 react 不同。
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时,必须使用多行代码。 最佳答案
这取决于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 {}
Quote:Henrik N来自“使用concat和捕获来清理定制的Rails助手”(http://thepugautomatic.com/2013/06/helpers/)
关于ruby-on-rails - Rails的concat方法和带有do ... end的块不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19319661/