Merged updates from trunk into stable branch
[feedcatcher.git] / vendor / rails / activerecord / lib / active_record / named_scope.rb
1 module ActiveRecord
2 module NamedScope
3 # All subclasses of ActiveRecord::Base have one named scope:
4 # * <tt>scoped</tt> - which allows for the creation of anonymous \scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
5 #
6 # These anonymous \scopes tend to be useful when procedurally generating complex queries, where passing
7 # intermediate values (scopes) around as first-class objects is convenient.
8 #
9 # You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.
10 def self.included(base)
11 base.class_eval do
12 extend ClassMethods
13 named_scope :scoped, lambda { |scope| scope }
14 end
15 end
16
17 module ClassMethods
18 def scopes
19 read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
20 end
21
22 # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
23 # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
24 #
25 # class Shirt < ActiveRecord::Base
26 # named_scope :red, :conditions => {:color => 'red'}
27 # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
28 # end
29 #
30 # The above calls to <tt>named_scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
31 # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
32 #
33 # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object
34 # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
35 # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
36 # as with the association objects, named \scopes act like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
37 # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really was an Array.
38 #
39 # 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.
40 # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
41 # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
42 #
43 # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which the \scopes were defined. But they are also available to
44 # <tt>has_many</tt> associations. If,
45 #
46 # class Person < ActiveRecord::Base
47 # has_many :shirts
48 # end
49 #
50 # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
51 # only shirts.
52 #
53 # Named \scopes can also be procedural:
54 #
55 # class Shirt < ActiveRecord::Base
56 # named_scope :colored, lambda { |color|
57 # { :conditions => { :color => color } }
58 # }
59 # end
60 #
61 # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
62 #
63 # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations:
64 #
65 # class Shirt < ActiveRecord::Base
66 # named_scope :red, :conditions => {:color => 'red'} do
67 # def dom_id
68 # 'red_shirts'
69 # end
70 # end
71 # end
72 #
73 #
74 # For testing complex named \scopes, you can examine the scoping options using the
75 # <tt>proxy_options</tt> method on the proxy itself.
76 #
77 # class Shirt < ActiveRecord::Base
78 # named_scope :colored, lambda { |color|
79 # { :conditions => { :color => color } }
80 # }
81 # end
82 #
83 # expected_options = { :conditions => { :colored => 'red' } }
84 # assert_equal expected_options, Shirt.colored('red').proxy_options
85 def named_scope(name, options = {}, &block)
86 name = name.to_sym
87 scopes[name] = lambda do |parent_scope, *args|
88 Scope.new(parent_scope, case options
89 when Hash
90 options
91 when Proc
92 case parent_scope
93 when Scope
94 with_scope(:find => parent_scope.proxy_options) { options.call(*args) }
95 else
96 options.call(*args)
97 end
98 end, &block)
99 end
100 (class << self; self end).instance_eval do
101 define_method name do |*args|
102 scopes[name].call(self, *args)
103 end
104 end
105 end
106 end
107
108 class Scope
109 attr_reader :proxy_scope, :proxy_options, :current_scoped_methods_when_defined
110 NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? respond_to?).to_set
111 [].methods.each do |m|
112 unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s)
113 delegate m, :to => :proxy_found
114 end
115 end
116
117 delegate :scopes, :with_scope, :to => :proxy_scope
118
119 def initialize(proxy_scope, options, &block)
120 options ||= {}
121 [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
122 extend Module.new(&block) if block_given?
123 unless Scope === proxy_scope
124 @current_scoped_methods_when_defined = proxy_scope.send(:current_scoped_methods)
125 end
126 @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
127 end
128
129 def reload
130 load_found; self
131 end
132
133 def first(*args)
134 if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
135 proxy_found.first(*args)
136 else
137 find(:first, *args)
138 end
139 end
140
141 def last(*args)
142 if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
143 proxy_found.last(*args)
144 else
145 find(:last, *args)
146 end
147 end
148
149 def size
150 @found ? @found.length : count
151 end
152
153 def empty?
154 @found ? @found.empty? : count.zero?
155 end
156
157 def respond_to?(method, include_private = false)
158 super || @proxy_scope.respond_to?(method, include_private)
159 end
160
161 def any?
162 if block_given?
163 proxy_found.any? { |*block_args| yield(*block_args) }
164 else
165 !empty?
166 end
167 end
168
169 protected
170 def proxy_found
171 @found || load_found
172 end
173
174 private
175 def method_missing(method, *args, &block)
176 if scopes.include?(method)
177 scopes[method].call(self, *args)
178 else
179 with_scope({:find => proxy_options, :create => proxy_options[:conditions].is_a?(Hash) ? proxy_options[:conditions] : {}}, :reverse_merge) do
180 method = :new if method == :build
181 if current_scoped_methods_when_defined
182 with_scope current_scoped_methods_when_defined do
183 proxy_scope.send(method, *args, &block)
184 end
185 else
186 proxy_scope.send(method, *args, &block)
187 end
188 end
189 end
190 end
191
192 def load_found
193 @found = find(:all)
194 end
195 end
196 end
197 end