Rails Views: Block Helper Example

Posted 2006-05-31…

A few articles back, I mentioned how useful helpers that take blocks can be within your views.

I thought I’d give a little example, giving a helper I find pretty useful in my own projects.

Here’s the code, which I’ll explain in a moment:

def link_to_section(name, html_opts={}, &block)
  section_id = name.underscore.gsub(/\s+/,'_')
  link_id = section_id + '_link'
  # Link
  concat(link_to_function(name,update_page{|page| 
    page[section_id].show
    page[link_id].hide
  }, html_opts.update(:id=>link_id)), block.binding)
  # Hidden section
  concat(tag('div', {:id=>section_id, :style=>'display:none;'},true),block.binding)
  yield update_page{|page| 
 page[section_id].hide
    page[link_id].show        
  }
  concat('</div>', block.binding)
end

What this makes possible is stuff like:

<% link_to_section("View Details") do |closer| %>
<h4>Details</h4>
<p>Some detailed text detailing detailed details.</p>
<%= link_to_function("Hide Details",closer) %>
<% end %>

What’s going on here is actually pretty simple. The helper generates a link (with the label you’ve given) to show a a hidden div and hide itself. The block given to the helper is what will end up inside that div, and it’s yielded the snippet of javascript necessary to switch back (so that you can use that snippet wherever you’d like).

Keep in mind assumes you’ll only have one link per page with the same label … if you think that won’t be the case, you’ll probably want ensure the ids generated inside the helper are unique; using object_id would be a simple way to do so.