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

 ̄綄美尐妖づ 提交于 2019-12-07 06:34:56

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/19319661/rails-concat-method-and-blocks-with-do-end-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!