Rails: What's the difference between capture and content_for?

ruby-on-rails

Solution

If you check out the content_for source, it calls capture internally:

def content_for(name, content = nil, &block)
  if content || block_given?
    content = capture(&block) if block_given?
    @view_flow.append(name, content) if content
    nil
  else
    @view_flow.get(name)
  end
end

So, from reading through the method, it looks like the primary advantage of content_for is that it can be called multiple times with multiple blocks for the same named content and each additional call will just append onto whatever has already been rendered. Whereas, in the case of capture, if you call:

<% @greeting = capture do %>
  Hello
<% end %>

and then later call:

<% @greeting = capture do %>
  Or, in espanol, Hola
<% end %>

Then the last part is the only part that will be captured, and the 'Hello' will just be discarded. Whereas, doing something similar in content_for will result in the second call being appended to 'Hello'.

Problem

In the Rails 3.2 CaptureHelper, what are the differences between using `capture` and `content_for`, and why would I choose one over the other?

Original source