Found Feature: Nested Scopes 2

Posted by Jeff Tue, 26 Dec 2006 05:58:00 GMT

While browsing A Single Programmer’s Blog I came across this article regarding a little known Rails feature (at least to me) called “Nested Scope”

Ultimately it allows you to turn code like this:

def self.find_by_active_and_paying(options={})
  conditions = Array.new
  conditions << 'active = 1'
  conditions << 'fee > 0'
  conditions << options[:conditions]
  self.find(:all, :conditions => [conditions.join(' AND '), options[:values])
end

Into this:

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 => {:conditions => 'active = 1'}) do
    yield
  end
end

def self.paying_scope 
  with_scope(:find => {:conditions => 'fee > 0'}) do
    yield
  end
end

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

For a fuller explanation check out these articles:

Comments

Leave a response

  1. casino online Wed, 28 Nov 2007 00:25:16 GMT
    Informationen über Neuigkeiten aus der Casino online Industrie, wo noch mit Schaufel und Pickel gearbeitet wird.
  2. internet casinos Sun, 09 Dec 2007 02:08:17 GMT
    Spielen Sie Internet Casinos entführt Sie in die Welt der Online Casinos und zeigt Ihnen, wo Sie sicher spielen können.
Comments