Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activerecord/lib/active_record/named_scope.rb

Revision 9084, 5.2 kB (checked in by rick, 7 months ago)

Merge the has_finder gem, renamed as 'named_scope'. Closes #11404 [nkallen]

Line 
1 module ActiveRecord
2   module NamedScope
3     # All subclasses of ActiveRecord::Base have two named_scopes:
4     # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
5     # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly:
6     #
7     #   Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)
8     #
9     # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
10     # intermediate values (scopes) around as first-class objects is convenient.
11     def self.included(base)
12       base.class_eval do
13         extend ClassMethods
14         named_scope :all
15         named_scope :scoped, lambda { |scope| scope }
16       end
17     end
18
19     module ClassMethods
20       def scopes
21         read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
22       end
23
24       # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
25       # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
26       #
27       #   class Shirt < ActiveRecord::Base
28       #     named_scope :red, :conditions => {:color => 'red'}
29       #     named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
30       #   end
31       #
32       # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
33       # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
34       #
35       # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
36       # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
37       # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
38       # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
39       # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
40       #
41       # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
42       # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
43       # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
44       #
45       # All scopes are available as class methods on the ActiveRecord descendent upon which the scopes were defined. But they are also available to
46       # <tt>has_many</tt> associations. If,
47       #
48       #   class Person < ActiveRecord::Base
49       #     has_many :shirts
50       #   end
51       #
52       # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
53       # only shirts.
54       #
55       # Named scopes can also be procedural.
56       #
57       #   class Shirt < ActiveRecord::Base
58       #     named_scope :colored, lambda { |color|
59       #       { :conditions => { :color => color } }
60       #     }
61       #   end
62       #
63       # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
64       #
65       # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
66       #
67       #   class Shirt < ActiveRecord::Base
68       #     named_scope :red, :conditions => {:color => 'red'} do
69       #       def dom_id
70       #         'red_shirts'
71       #       end
72       #     end
73       #   end
74       #
75       def named_scope(name, options = {}, &block)
76         scopes[name] = lambda do |parent_scope, *args|
77           Scope.new(parent_scope, case options
78             when Hash
79               options
80             when Proc
81               options.call(*args)
82           end, &block)
83         end
84         (class << self; self end).instance_eval do
85           define_method name do |*args|
86             scopes[name].call(self, *args)
87           end
88         end
89       end
90     end
91    
92     class Scope
93       attr_reader :proxy_scope, :proxy_options
94       [].methods.each { |m| delegate m, :to => :proxy_found unless m =~ /(^__|^nil\?|^send|class|extend|find|count|sum|average|maximum|minimum|paginate)/ }
95       delegate :scopes, :with_scope, :to => :proxy_scope
96
97       def initialize(proxy_scope, options, &block)
98         [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
99         extend Module.new(&block) if block_given?
100         @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
101       end
102
103       def reload
104         load_found; self
105       end
106
107       protected
108       def proxy_found
109         @found || load_found
110       end
111
112       private
113       def method_missing(method, *args, &block)
114         if scopes.include?(method)
115           scopes[method].call(self, *args)
116         else
117           with_scope :find => proxy_options do
118             proxy_scope.send(method, *args, &block)
119           end
120         end
121       end
122
123       def load_found
124         @found = find(:all)
125       end
126     end
127   end
128 end
Note: See TracBrowser for help on using the browser.