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