<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: blocks code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 27 Jul 2008 00:54:58 GMT</pubDate>
    <description>DZone Snippets: blocks code</description>
    <item>
      <title>Block to Partial Rails Helper</title>
      <link>http://snippets.dzone.com/posts/show/2483</link>
      <description>From &lt;a href="http://errtheblog.com/post/13"&gt;http://errtheblog.com/post/13&lt;/a&gt;.&lt;br /&gt;Create a helper which takes a block and renders that block within the context of a partial.&lt;br /&gt;&lt;br /&gt;Create this helper:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def block_to_partial(partial_name, options = {}, &amp;block)&lt;br /&gt;  options.merge!(:body =&gt; capture(&amp;block))&lt;br /&gt;  concat(render(:partial =&gt; partial_name, :locals =&gt; options), block.binding)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Create this helper, too:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def sidebar_module(title, options = {}, &amp;block)&lt;br /&gt;  block_to_partial('shared/sidebar_module', options.merge(:title =&gt; title), &amp;block)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Create this partial (app/views/shared/_sidebar_module.rhtml):&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;div &lt;%= %[id="#{id}"] unless id.blank? %&gt; class="sidebar_module"&gt;&lt;br /&gt;  &lt;h2&gt;&lt;%= title %&gt;&lt;/h2&gt;&lt;br /&gt;  &lt;%= body %&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Use it in your views:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;% sidebar_module 'Recent Stories' do %&gt;&lt;br /&gt;  &lt;%= render :partial =&gt; 'recent_stories', :collection =&gt; @recent_stories %&gt;&lt;br /&gt;&lt;% end %&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 28 Aug 2006 05:49:13 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2483</guid>
      <author>err (Chris Wanstrath)</author>
    </item>
  </channel>
</rss>
