named.rb 7.0 KB
Newer Older
1 2 3 4 5
require 'active_support/core_ext/array'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/kernel/singleton_class'

module ActiveRecord
6
  # = Active Record \Named \Scopes
7 8 9 10 11
  module Scoping
    module Named
      extend ActiveSupport::Concern

      module ClassMethods
12
        # Returns an ActiveRecord::Relation scope object.
13
        #
14
        #   posts = Post.all
15 16 17
        #   posts.size # Fires "select count(*) from  posts" and returns the count
        #   posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
        #
18
        #   fruits = Fruit.all
19
        #   fruits = fruits.where(color: 'red') if options[:red_only]
20 21
        #   fruits = fruits.limit(10) if limited?
        #
22
        # You can define a scope that applies to all finders using
23
        # {default_scope}[rdoc-ref:Scoping::Default::ClassMethods#default_scope].
24
        def all
J
Jon Leighton 已提交
25
          if current_scope
26
            current_scope.clone
27
          else
28
            default_scoped
29
          end
30
        end
J
Jon Leighton 已提交
31

32
        def default_scoped # :nodoc:
33 34 35 36 37 38 39
          scope = build_default_scope

          if scope
            relation.spawn.merge!(scope)
          else
            relation
          end
40 41
        end

42
        # Adds a class method for retrieving and querying objects.
43
        # The method is intended to return an ActiveRecord::Relation
44
        # object, which is composable with other scopes.
45 46
        # If it returns nil or false, an
        # {all}[rdoc-ref:Scoping::Named::ClassMethods#all] scope is returned instead.
47 48
        #
        # A \scope represents a narrowing of a database query, such as
49
        # <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
50 51
        #
        #   class Shirt < ActiveRecord::Base
52 53
        #     scope :red, -> { where(color: 'red') }
        #     scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
54 55
        #   end
        #
56
        # The above calls to #scope define class methods <tt>Shirt.red</tt> and
57 58
        # <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
        # represents the query <tt>Shirt.where(color: 'red')</tt>.
59
        #
60
        # You should always pass a callable object to the scopes defined
61
        # with #scope. This ensures that the scope is re-evaluated each
62 63 64 65
        # time it is called.
        #
        # Note that this is simply 'syntactic sugar' for defining an actual
        # class method:
66 67 68
        #
        #   class Shirt < ActiveRecord::Base
        #     def self.red
69
        #       where(color: 'red')
70 71 72
        #     end
        #   end
        #
73
        # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
74
        # <tt>Shirt.red</tt> is not an Array but an ActiveRecord::Relation,
75
        # which is composable with other scopes; it resembles the association object
76 77
        # constructed by a {has_many}[rdoc-ref:Associations::ClassMethods#has_many]
        # declaration. For instance, you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
78 79 80 81
        # <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
        # association objects, named \scopes act like an Array, implementing
        # Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
        # and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
82
        # <tt>Shirt.red</tt> really was an array.
83 84 85 86 87 88 89 90 91 92
        #
        # 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. Nested finds and calculations also work
        # with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
        # returns the number of garments for which these criteria obtain.
        # Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
        #
        # All scopes are available as class methods on the ActiveRecord::Base
        # descendant upon which the \scopes were defined. But they are also
93 94
        # available to {has_many}[rdoc-ref:Associations::ClassMethods#has_many]
        # associations. If,
95 96 97 98 99
        #
        #   class Person < ActiveRecord::Base
        #     has_many :shirts
        #   end
        #
100 101
        # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
        # Elton's red, dry clean only shirts.
102
        #
103 104
        # \Named scopes can also have extensions, just as with
        # {has_many}[rdoc-ref:Associations::ClassMethods#has_many] declarations:
105 106
        #
        #   class Shirt < ActiveRecord::Base
107
        #     scope :red, -> { where(color: 'red') } do
108 109 110 111 112 113 114 115 116
        #       def dom_id
        #         'red_shirts'
        #       end
        #     end
        #   end
        #
        # Scopes can also be used while creating/building a record.
        #
        #   class Article < ActiveRecord::Base
117
        #     scope :published, -> { where(published: true) }
118 119 120 121 122
        #   end
        #
        #   Article.published.new.published    # => true
        #   Article.published.create.published # => true
        #
123
        # \Class methods on your model are automatically available
124 125 126
        # on scopes. Assuming the following setup:
        #
        #   class Article < ActiveRecord::Base
127
        #     scope :published, -> { where(published: true) }
128
        #     scope :featured, -> { where(featured: true) }
129 130 131 132 133 134
        #
        #     def self.latest_article
        #       order('published_at desc').first
        #     end
        #
        #     def self.titles
135
        #       pluck(:title)
136 137 138 139 140 141 142
        #     end
        #   end
        #
        # We are able to call the methods like this:
        #
        #   Article.published.featured.latest_article
        #   Article.featured.titles
J
Jon Leighton 已提交
143
        def scope(name, body, &block)
A
Andrey Deryabin 已提交
144
          unless body.respond_to?(:call)
145 146
            raise ArgumentError, 'The scope body needs to be callable.'
          end
147

148 149 150 151 152 153
          if dangerous_class_method?(name)
            raise ArgumentError, "You tried to define a scope named \"#{name}\" " \
              "on the model \"#{self.name}\", but Active Record already defined " \
              "a class method with the same name."
          end

154
          valid_scope_name?(name)
J
Jon Leighton 已提交
155
          extension = Module.new(&block) if block
156

157 158 159 160
          if body.respond_to?(:to_proc)
            singleton_class.send(:define_method, name) do |*args|
              scope = all.scoping { instance_exec(*args, &body) }
              scope = scope.extending(extension) if extension
161

162 163 164 165 166 167 168 169 170
              scope || all
            end
          else
            singleton_class.send(:define_method, name) do |*args|
              scope = all.scoping { body.call(*args) }
              scope = scope.extending(extension) if extension

              scope || all
            end
171 172
          end
        end
173 174 175 176

      protected

        def valid_scope_name?(name)
177
          if respond_to?(name, true) && logger
178 179 180 181
            logger.warn "Creating scope :#{name}. " \
                        "Overwriting existing method #{self.name}.#{name}."
          end
        end
182 183 184 185
      end
    end
  end
end