I just read about Rails' concat
method to clean up helpers that output something here http://thepugautomatic.com/2013/06/helpers/.
I played around with it, and I have found out, that it doesn't react the same way to blocks with curly braces and to blocks with 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
I didn't know that curly braces and do...end blocks seem to have different meanings. Is there a way to use concat
with do...end without putting parenthesis around it (3rd example)? Otherwise it seems to be pretty useless for certain situations, e.g. when I want to concat an UL with many LI elements in it, so I have to use more than one line of code.
It comes down to Ruby's scoping. With concat content_tag :strong do "hello" end
, the block is passed to concat
, not to content_tag
.
Toy around with this code and you'll see:
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 from "Using concat and capture to clean up custom Rails helpers" (http://thepugautomatic.com/2013/06/helpers/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With