Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails' concat method and blocks with do...end doesn't work

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.

like image 864
Joshua Muheim Avatar asked Oct 11 '13 13:10

Joshua Muheim


1 Answers

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/)

like image 157
Joshua Muheim Avatar answered Nov 02 '22 11:11

Joshua Muheim