Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a helper method yield to a block in rails 3?

I have used this pattern for a number of helpers in rails 2, but it isn't working the same in rails 3. My goal is to have a helper method generate some html tags with content nested inside. Here is a basic example of what I'm trying to get:

<div class="box">
  my content
</div>

In rails 2 I do it like this:

inside my layout file I call the helper method:

  <% box_wrapper do %>
    <%= yield -%>
  <% end %>

The helper method is defined like this:

def box_wrapper
  concat <<-EOF.html_safe
    <div class="box">
  EOF

  yield  if block_given?
  concat <<-EOF.html_safe
    </div>
  EOF
end

But in rails 3 when the view gets rendered it outputs my entire page and then inside the box_wrapper it renders all of the page content a 2nd time.

I think I'm missing something obvious with how to use helpers and yields. Any ideas?

like image 971
nimblegorilla Avatar asked Apr 04 '11 15:04

nimblegorilla


1 Answers

In Rails 3, you no longer need to use the concat method to build the content of your blocks.

Your helper now looks like this:

def box_wrapper(&block)  
  content = capture(&block)  
  content_tag(:div, content, :class => 'box')  
end

You can see other examples in Railscasts 208.

like image 55
Douglas F Shearer Avatar answered Sep 27 '22 20:09

Douglas F Shearer