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
Block To Partial Rails Helper
From <a href="http://errtheblog.com/post/13">http://errtheblog.com/post/13</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)
end
Create this helper, too:
def sidebar_module(title, options = {}, &block)
block_to_partial('shared/sidebar_module', options.merge(:title => title), &block)
end
Create this partial (app/views/shared/_sidebar_module.rhtml):
<div <%= %[id="#{id}"] unless id.blank? %> class="sidebar_module">
<h2><%= title %></h2>
<%= body %>
</div>
Use it in your views:
<% sidebar_module 'Recent Stories' do %> <%= render :partial => 'recent_stories', :collection => @recent_stories %> <% end %>





