DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Block To Partial Rails Helper

  • submit to reddit
        From <a href=""></a>.
Create a helper which takes a block and renders that block within the context of a partial.

Create this helper:
def block_to_partial(partial_name, options = {}, &block)
  options.merge!(:body => capture(&block))
  concat(render(:partial => partial_name, :locals => options), block.binding)

Create this helper, too:
def sidebar_module(title, options = {}, &block)
  block_to_partial('shared/sidebar_module', options.merge(:title => title), &block)

Create this partial (app/views/shared/_sidebar_module.rhtml):
<div <%= %[id="#{id}"] unless id.blank? %> class="sidebar_module">
  <h2><%= title %></h2>
  <%= body %>

Use it in your views:
<% sidebar_module 'Recent Stories' do %>
  <%= render :partial => 'recent_stories', :collection => @recent_stories %>
<% end %>