<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>The Bacon Bear Blog: Found Feature: Nested Scopes</title>
    <link>http://www.baconbear.com/articles/2006/12/25/found-feature-nested-scopes</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Found Feature: Nested Scopes</title>
      <description>&lt;p&gt;While browsing &lt;a href="http://blog.teksol.info/"&gt;A Single Programmer&amp;#8217;s Blog&lt;/a&gt; I came across this &lt;a href="http://blog.teksol.info/articles/2006/04/14/using-nested-scopes-to-not-repeat-yourself"&gt;article&lt;/a&gt; regarding a little known Rails feature (at least to me) called &amp;#8220;Nested Scope&amp;#8221;&lt;/p&gt;

&lt;p&gt;Ultimately it allows you to turn code like this:&lt;/p&gt;

&lt;pre&gt;
def self.find_by_active_and_paying(options={})
  conditions = Array.new
  conditions &lt;&lt; 'active = 1'
  conditions &lt;&lt; 'fee &gt; 0'
  conditions &lt;&lt; options[:conditions]
  self.find(:all, :conditions =&gt; [conditions.join(' AND '), options[:values])
end
&lt;/pre&gt;

&lt;p&gt;Into this:&lt;/p&gt;

&lt;pre&gt;
def self.find_by_active_and_paying(options={})
  active_scope do
    paying_scope do
      self.find(:all, options)
    end
  end
end

protected
def self.active_scope 
  with_scope(:find =&gt; {:conditions =&gt; 'active = 1'}) do
    yield
  end
end

def self.paying_scope 
  with_scope(:find =&gt; {:conditions =&gt; 'fee &gt; 0'}) do
    yield
  end
end
&lt;/pre&gt;

&lt;p&gt;Notice how the build up of conditions is gone and instead replaced with *_scope calls.  This has great implications for keeping with DRY principles.&lt;/p&gt;

&lt;p&gt;For a fuller explanation check out these articles: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://blog.teksol.info/articles/2006/04/14/using-nested-scopes-to-not-repeat-yourself"&gt;A Single Programmers Blog&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.codyfauser.com/articles/2006/02/01/using-with_scope-to-refactor-messy-finders"&gt;Codey Fauser&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M000754"&gt;Rails Docs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description>
      <pubDate>Mon, 25 Dec 2006 21:58:00 -0800</pubDate>
      <guid isPermaLink="false">urn:uuid:e1ba5e5a-857d-4612-9e82-b4efc8245edc</guid>
      <author>Jeff</author>
      <link>http://www.baconbear.com/articles/2006/12/25/found-feature-nested-scopes</link>
      <category>rails</category>
    </item>
  </channel>
</rss>
