Found Feature: Nested Scopes 2
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
-
Informationen über Neuigkeiten aus der Casino online Industrie, wo noch mit Schaufel und Pickel gearbeitet wird.
-
Spielen Sie Internet Casinos entführt Sie in die Welt der Online Casinos und zeigt Ihnen, wo Sie sicher spielen können.
