sskirby-activerecord 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. data/CHANGELOG.md +6749 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +222 -0
  4. data/examples/associations.png +0 -0
  5. data/examples/performance.rb +177 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +147 -0
  8. data/lib/active_record/aggregations.rb +255 -0
  9. data/lib/active_record/associations.rb +1604 -0
  10. data/lib/active_record/associations/alias_tracker.rb +79 -0
  11. data/lib/active_record/associations/association.rb +239 -0
  12. data/lib/active_record/associations/association_scope.rb +119 -0
  13. data/lib/active_record/associations/belongs_to_association.rb +79 -0
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +34 -0
  15. data/lib/active_record/associations/builder/association.rb +55 -0
  16. data/lib/active_record/associations/builder/belongs_to.rb +85 -0
  17. data/lib/active_record/associations/builder/collection_association.rb +75 -0
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
  19. data/lib/active_record/associations/builder/has_many.rb +71 -0
  20. data/lib/active_record/associations/builder/has_one.rb +62 -0
  21. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  22. data/lib/active_record/associations/collection_association.rb +574 -0
  23. data/lib/active_record/associations/collection_proxy.rb +132 -0
  24. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +62 -0
  25. data/lib/active_record/associations/has_many_association.rb +108 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +180 -0
  27. data/lib/active_record/associations/has_one_association.rb +73 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +214 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +154 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  33. data/lib/active_record/associations/join_helper.rb +55 -0
  34. data/lib/active_record/associations/preloader.rb +177 -0
  35. data/lib/active_record/associations/preloader/association.rb +127 -0
  36. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  37. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  38. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  39. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  40. data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
  41. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  42. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  43. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  44. data/lib/active_record/associations/preloader/through_association.rb +67 -0
  45. data/lib/active_record/associations/singular_association.rb +64 -0
  46. data/lib/active_record/associations/through_association.rb +83 -0
  47. data/lib/active_record/attribute_assignment.rb +221 -0
  48. data/lib/active_record/attribute_methods.rb +272 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
  50. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  51. data/lib/active_record/attribute_methods/dirty.rb +101 -0
  52. data/lib/active_record/attribute_methods/primary_key.rb +114 -0
  53. data/lib/active_record/attribute_methods/query.rb +39 -0
  54. data/lib/active_record/attribute_methods/read.rb +135 -0
  55. data/lib/active_record/attribute_methods/serialization.rb +93 -0
  56. data/lib/active_record/attribute_methods/time_zone_conversion.rb +62 -0
  57. data/lib/active_record/attribute_methods/write.rb +69 -0
  58. data/lib/active_record/autosave_association.rb +422 -0
  59. data/lib/active_record/base.rb +716 -0
  60. data/lib/active_record/callbacks.rb +275 -0
  61. data/lib/active_record/coders/yaml_column.rb +41 -0
  62. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +452 -0
  63. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +188 -0
  64. data/lib/active_record/connection_adapters/abstract/database_limits.rb +58 -0
  65. data/lib/active_record/connection_adapters/abstract/database_statements.rb +388 -0
  66. data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -0
  67. data/lib/active_record/connection_adapters/abstract/quoting.rb +115 -0
  68. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +492 -0
  69. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +598 -0
  70. data/lib/active_record/connection_adapters/abstract_adapter.rb +296 -0
  71. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
  72. data/lib/active_record/connection_adapters/column.rb +270 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +288 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +426 -0
  75. data/lib/active_record/connection_adapters/postgresql_adapter.rb +1261 -0
  76. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  77. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +55 -0
  78. data/lib/active_record/connection_adapters/sqlite_adapter.rb +577 -0
  79. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  80. data/lib/active_record/counter_cache.rb +119 -0
  81. data/lib/active_record/dynamic_finder_match.rb +56 -0
  82. data/lib/active_record/dynamic_matchers.rb +79 -0
  83. data/lib/active_record/dynamic_scope_match.rb +23 -0
  84. data/lib/active_record/errors.rb +195 -0
  85. data/lib/active_record/explain.rb +85 -0
  86. data/lib/active_record/explain_subscriber.rb +21 -0
  87. data/lib/active_record/fixtures.rb +906 -0
  88. data/lib/active_record/fixtures/file.rb +65 -0
  89. data/lib/active_record/identity_map.rb +156 -0
  90. data/lib/active_record/inheritance.rb +167 -0
  91. data/lib/active_record/integration.rb +49 -0
  92. data/lib/active_record/locale/en.yml +40 -0
  93. data/lib/active_record/locking/optimistic.rb +183 -0
  94. data/lib/active_record/locking/pessimistic.rb +77 -0
  95. data/lib/active_record/log_subscriber.rb +68 -0
  96. data/lib/active_record/migration.rb +765 -0
  97. data/lib/active_record/migration/command_recorder.rb +105 -0
  98. data/lib/active_record/model_schema.rb +366 -0
  99. data/lib/active_record/nested_attributes.rb +469 -0
  100. data/lib/active_record/observer.rb +121 -0
  101. data/lib/active_record/persistence.rb +372 -0
  102. data/lib/active_record/query_cache.rb +74 -0
  103. data/lib/active_record/querying.rb +58 -0
  104. data/lib/active_record/railtie.rb +119 -0
  105. data/lib/active_record/railties/console_sandbox.rb +6 -0
  106. data/lib/active_record/railties/controller_runtime.rb +49 -0
  107. data/lib/active_record/railties/databases.rake +620 -0
  108. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  109. data/lib/active_record/readonly_attributes.rb +26 -0
  110. data/lib/active_record/reflection.rb +534 -0
  111. data/lib/active_record/relation.rb +534 -0
  112. data/lib/active_record/relation/batches.rb +90 -0
  113. data/lib/active_record/relation/calculations.rb +354 -0
  114. data/lib/active_record/relation/delegation.rb +49 -0
  115. data/lib/active_record/relation/finder_methods.rb +398 -0
  116. data/lib/active_record/relation/predicate_builder.rb +58 -0
  117. data/lib/active_record/relation/query_methods.rb +417 -0
  118. data/lib/active_record/relation/spawn_methods.rb +148 -0
  119. data/lib/active_record/result.rb +34 -0
  120. data/lib/active_record/sanitization.rb +194 -0
  121. data/lib/active_record/schema.rb +58 -0
  122. data/lib/active_record/schema_dumper.rb +204 -0
  123. data/lib/active_record/scoping.rb +152 -0
  124. data/lib/active_record/scoping/default.rb +142 -0
  125. data/lib/active_record/scoping/named.rb +202 -0
  126. data/lib/active_record/serialization.rb +18 -0
  127. data/lib/active_record/serializers/xml_serializer.rb +202 -0
  128. data/lib/active_record/session_store.rb +358 -0
  129. data/lib/active_record/store.rb +50 -0
  130. data/lib/active_record/test_case.rb +73 -0
  131. data/lib/active_record/timestamp.rb +113 -0
  132. data/lib/active_record/transactions.rb +360 -0
  133. data/lib/active_record/translation.rb +22 -0
  134. data/lib/active_record/validations.rb +83 -0
  135. data/lib/active_record/validations/associated.rb +43 -0
  136. data/lib/active_record/validations/uniqueness.rb +180 -0
  137. data/lib/active_record/version.rb +10 -0
  138. data/lib/rails/generators/active_record.rb +25 -0
  139. data/lib/rails/generators/active_record/migration.rb +15 -0
  140. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  141. data/lib/rails/generators/active_record/migration/templates/migration.rb +31 -0
  142. data/lib/rails/generators/active_record/model/model_generator.rb +43 -0
  143. data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
  144. data/lib/rails/generators/active_record/model/templates/model.rb +7 -0
  145. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  146. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  147. data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
  148. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
  149. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
  150. metadata +242 -0
@@ -0,0 +1,152 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveRecord
4
+ module Scoping
5
+ extend ActiveSupport::Concern
6
+
7
+ included do
8
+ include Default
9
+ include Named
10
+ end
11
+
12
+ module ClassMethods
13
+ # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be
14
+ # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
15
+ # <tt>:create</tt> parameters are an attributes hash.
16
+ #
17
+ # class Article < ActiveRecord::Base
18
+ # def self.create_with_scope
19
+ # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do
20
+ # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
21
+ # a = create(1)
22
+ # a.blog_id # => 1
23
+ # end
24
+ # end
25
+ # end
26
+ #
27
+ # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
28
+ # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged.
29
+ #
30
+ # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing
31
+ # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the
32
+ # array of strings format for your joins.
33
+ #
34
+ # class Article < ActiveRecord::Base
35
+ # def self.find_with_scope
36
+ # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do
37
+ # with_scope(:find => limit(10)) do
38
+ # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
39
+ # end
40
+ # with_scope(:find => where(:author_id => 3)) do
41
+ # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
42
+ # end
43
+ # end
44
+ # end
45
+ # end
46
+ #
47
+ # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
48
+ #
49
+ # class Article < ActiveRecord::Base
50
+ # def self.find_with_exclusive_scope
51
+ # with_scope(:find => where(:blog_id => 1).limit(1)) do
52
+ # with_exclusive_scope(:find => limit(10)) do
53
+ # all # => SELECT * from articles LIMIT 10
54
+ # end
55
+ # end
56
+ # end
57
+ # end
58
+ #
59
+ # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+.
60
+ def with_scope(scope = {}, action = :merge, &block)
61
+ # If another Active Record class has been passed in, get its current scope
62
+ scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope)
63
+
64
+ previous_scope = self.current_scope
65
+
66
+ if scope.is_a?(Hash)
67
+ # Dup first and second level of hash (method and params).
68
+ scope = scope.dup
69
+ scope.each do |method, params|
70
+ scope[method] = params.dup unless params == true
71
+ end
72
+
73
+ scope.assert_valid_keys([ :find, :create ])
74
+ relation = construct_finder_arel(scope[:find] || {})
75
+ relation.default_scoped = true unless action == :overwrite
76
+
77
+ if previous_scope && previous_scope.create_with_value && scope[:create]
78
+ scope_for_create = if action == :merge
79
+ previous_scope.create_with_value.merge(scope[:create])
80
+ else
81
+ scope[:create]
82
+ end
83
+
84
+ relation = relation.create_with(scope_for_create)
85
+ else
86
+ scope_for_create = scope[:create]
87
+ scope_for_create ||= previous_scope.create_with_value if previous_scope
88
+ relation = relation.create_with(scope_for_create) if scope_for_create
89
+ end
90
+
91
+ scope = relation
92
+ end
93
+
94
+ scope = previous_scope.merge(scope) if previous_scope && action == :merge
95
+
96
+ self.current_scope = scope
97
+ begin
98
+ yield
99
+ ensure
100
+ self.current_scope = previous_scope
101
+ end
102
+ end
103
+
104
+ protected
105
+
106
+ # Works like with_scope, but discards any nested properties.
107
+ def with_exclusive_scope(method_scoping = {}, &block)
108
+ if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) }
109
+ raise ArgumentError, <<-MSG
110
+ New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope:
111
+
112
+ User.unscoped.where(:active => true)
113
+
114
+ Or call unscoped with a block:
115
+
116
+ User.unscoped do
117
+ User.where(:active => true).all
118
+ end
119
+
120
+ MSG
121
+ end
122
+ with_scope(method_scoping, :overwrite, &block)
123
+ end
124
+
125
+ def current_scope #:nodoc:
126
+ Thread.current["#{self}_current_scope"]
127
+ end
128
+
129
+ def current_scope=(scope) #:nodoc:
130
+ Thread.current["#{self}_current_scope"] = scope
131
+ end
132
+
133
+ private
134
+
135
+ def construct_finder_arel(options = {}, scope = nil)
136
+ relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options
137
+ relation = scope.merge(relation) if scope
138
+ relation
139
+ end
140
+
141
+ end
142
+
143
+ def populate_with_current_scope_attributes
144
+ return unless self.class.scope_attributes?
145
+
146
+ self.class.scope_attributes.each do |att,value|
147
+ send("#{att}=", value) if respond_to?("#{att}=")
148
+ end
149
+ end
150
+
151
+ end
152
+ end
@@ -0,0 +1,142 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveRecord
4
+ module Scoping
5
+ module Default
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ # Stores the default scope for the class
10
+ class_attribute :default_scopes, :instance_writer => false
11
+ self.default_scopes = []
12
+ end
13
+
14
+ module ClassMethods
15
+ # Returns a scope for the model without the default_scope.
16
+ #
17
+ # class Post < ActiveRecord::Base
18
+ # def self.default_scope
19
+ # where :published => true
20
+ # end
21
+ # end
22
+ #
23
+ # Post.all # Fires "SELECT * FROM posts WHERE published = true"
24
+ # Post.unscoped.all # Fires "SELECT * FROM posts"
25
+ #
26
+ # This method also accepts a block. All queries inside the block will
27
+ # not use the default_scope:
28
+ #
29
+ # Post.unscoped {
30
+ # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
31
+ # }
32
+ #
33
+ # It is recommended to use the block form of unscoped because chaining
34
+ # unscoped with <tt>scope</tt> does not work. Assuming that
35
+ # <tt>published</tt> is a <tt>scope</tt>, the following two statements
36
+ # are equal: the default_scope is applied on both.
37
+ #
38
+ # Post.unscoped.published
39
+ # Post.published
40
+ def unscoped #:nodoc:
41
+ block_given? ? relation.scoping { yield } : relation
42
+ end
43
+
44
+ def before_remove_const #:nodoc:
45
+ self.current_scope = nil
46
+ end
47
+
48
+ protected
49
+
50
+ # Use this macro in your model to set a default scope for all operations on
51
+ # the model.
52
+ #
53
+ # class Article < ActiveRecord::Base
54
+ # default_scope where(:published => true)
55
+ # end
56
+ #
57
+ # Article.all # => SELECT * FROM articles WHERE published = true
58
+ #
59
+ # The <tt>default_scope</tt> is also applied while creating/building a record. It is not
60
+ # applied while updating a record.
61
+ #
62
+ # Article.new.published # => true
63
+ # Article.create.published # => true
64
+ #
65
+ # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated:
66
+ #
67
+ # class Article < ActiveRecord::Base
68
+ # default_scope { where(:published_at => Time.now - 1.week) }
69
+ # end
70
+ #
71
+ # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt>
72
+ # macro, and it will be called when building the default scope.)
73
+ #
74
+ # If you use multiple <tt>default_scope</tt> declarations in your model then they will
75
+ # be merged together:
76
+ #
77
+ # class Article < ActiveRecord::Base
78
+ # default_scope where(:published => true)
79
+ # default_scope where(:rating => 'G')
80
+ # end
81
+ #
82
+ # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
83
+ #
84
+ # This is also the case with inheritance and module includes where the parent or module
85
+ # defines a <tt>default_scope</tt> and the child or including class defines a second one.
86
+ #
87
+ # If you need to do more complex things with a default scope, you can alternatively
88
+ # define it as a class method:
89
+ #
90
+ # class Article < ActiveRecord::Base
91
+ # def self.default_scope
92
+ # # Should return a scope, you can call 'super' here etc.
93
+ # end
94
+ # end
95
+ def default_scope(scope = {})
96
+ scope = Proc.new if block_given?
97
+ self.default_scopes = default_scopes + [scope]
98
+ end
99
+
100
+ def build_default_scope #:nodoc:
101
+ if method(:default_scope).owner != ActiveRecord::Scoping::Default::ClassMethods
102
+ evaluate_default_scope { default_scope }
103
+ elsif default_scopes.any?
104
+ evaluate_default_scope do
105
+ default_scopes.inject(relation) do |default_scope, scope|
106
+ if scope.is_a?(Hash)
107
+ default_scope.apply_finder_options(scope)
108
+ elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
109
+ default_scope.merge(scope.call)
110
+ else
111
+ default_scope.merge(scope)
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+
118
+ def ignore_default_scope? #:nodoc:
119
+ Thread.current["#{self}_ignore_default_scope"]
120
+ end
121
+
122
+ def ignore_default_scope=(ignore) #:nodoc:
123
+ Thread.current["#{self}_ignore_default_scope"] = ignore
124
+ end
125
+
126
+ # The ignore_default_scope flag is used to prevent an infinite recursion situation where
127
+ # a default scope references a scope which has a default scope which references a scope...
128
+ def evaluate_default_scope
129
+ return if ignore_default_scope?
130
+
131
+ begin
132
+ self.ignore_default_scope = true
133
+ yield
134
+ ensure
135
+ self.ignore_default_scope = false
136
+ end
137
+ end
138
+
139
+ end
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,202 @@
1
+ require 'active_support/core_ext/array'
2
+ require 'active_support/core_ext/hash/except'
3
+ require 'active_support/core_ext/kernel/singleton_class'
4
+ require 'active_support/core_ext/object/blank'
5
+ require 'active_support/core_ext/class/attribute'
6
+
7
+ module ActiveRecord
8
+ # = Active Record Named \Scopes
9
+ module Scoping
10
+ module Named
11
+ extend ActiveSupport::Concern
12
+
13
+ module ClassMethods
14
+ # Returns an anonymous \scope.
15
+ #
16
+ # posts = Post.scoped
17
+ # posts.size # Fires "select count(*) from posts" and returns the count
18
+ # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
19
+ #
20
+ # fruits = Fruit.scoped
21
+ # fruits = fruits.where(:color => 'red') if options[:red_only]
22
+ # fruits = fruits.limit(10) if limited?
23
+ #
24
+ # Anonymous \scopes tend to be useful when procedurally generating complex
25
+ # queries, where passing intermediate values (\scopes) around as first-class
26
+ # objects is convenient.
27
+ #
28
+ # You can define a \scope that applies to all finders using
29
+ # ActiveRecord::Base.default_scope.
30
+ def scoped(options = nil)
31
+ if options
32
+ scoped.apply_finder_options(options)
33
+ else
34
+ if current_scope
35
+ current_scope.clone
36
+ else
37
+ scope = relation.clone
38
+ scope.default_scoped = true
39
+ scope
40
+ end
41
+ end
42
+ end
43
+
44
+ ##
45
+ # Collects attributes from scopes that should be applied when creating
46
+ # an AR instance for the particular class this is called on.
47
+ def scope_attributes # :nodoc:
48
+ if current_scope
49
+ current_scope.scope_for_create
50
+ else
51
+ scope = relation.clone
52
+ scope.default_scoped = true
53
+ scope.scope_for_create
54
+ end
55
+ end
56
+
57
+ ##
58
+ # Are there default attributes associated with this scope?
59
+ def scope_attributes? # :nodoc:
60
+ current_scope || default_scopes.any?
61
+ end
62
+
63
+ # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query,
64
+ # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>.
65
+ #
66
+ # class Shirt < ActiveRecord::Base
67
+ # scope :red, where(:color => 'red')
68
+ # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)
69
+ # end
70
+ #
71
+ # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
72
+ # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
73
+ #
74
+ # Note that this is simply 'syntactic sugar' for defining an actual class method:
75
+ #
76
+ # class Shirt < ActiveRecord::Base
77
+ # def self.red
78
+ # where(:color => 'red')
79
+ # end
80
+ # end
81
+ #
82
+ # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
83
+ # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
84
+ # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
85
+ # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
86
+ # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
87
+ # all behave as if Shirt.red really was an Array.
88
+ #
89
+ # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
90
+ # all shirts that are both red and dry clean only.
91
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
92
+ # returns the number of garments for which these criteria obtain. Similarly with
93
+ # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
94
+ #
95
+ # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
96
+ # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
97
+ #
98
+ # class Person < ActiveRecord::Base
99
+ # has_many :shirts
100
+ # end
101
+ #
102
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
103
+ # only shirts.
104
+ #
105
+ # Named \scopes can also be procedural:
106
+ #
107
+ # class Shirt < ActiveRecord::Base
108
+ # scope :colored, lambda { |color| where(:color => color) }
109
+ # end
110
+ #
111
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
112
+ #
113
+ # On Ruby 1.9 you can use the 'stabby lambda' syntax:
114
+ #
115
+ # scope :colored, ->(color) { where(:color => color) }
116
+ #
117
+ # Note that scopes defined with \scope will be evaluated when they are defined, rather than
118
+ # when they are used. For example, the following would be incorrect:
119
+ #
120
+ # class Post < ActiveRecord::Base
121
+ # scope :recent, where('published_at >= ?', Time.current - 1.week)
122
+ # end
123
+ #
124
+ # The example above would be 'frozen' to the <tt>Time.current</tt> value when the <tt>Post</tt>
125
+ # class was defined, and so the resultant SQL query would always be the same. The correct
126
+ # way to do this would be via a lambda, which will re-evaluate the scope each time
127
+ # it is called:
128
+ #
129
+ # class Post < ActiveRecord::Base
130
+ # scope :recent, lambda { where('published_at >= ?', Time.current - 1.week) }
131
+ # end
132
+ #
133
+ # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations:
134
+ #
135
+ # class Shirt < ActiveRecord::Base
136
+ # scope :red, where(:color => 'red') do
137
+ # def dom_id
138
+ # 'red_shirts'
139
+ # end
140
+ # end
141
+ # end
142
+ #
143
+ # Scopes can also be used while creating/building a record.
144
+ #
145
+ # class Article < ActiveRecord::Base
146
+ # scope :published, where(:published => true)
147
+ # end
148
+ #
149
+ # Article.published.new.published # => true
150
+ # Article.published.create.published # => true
151
+ #
152
+ # Class methods on your model are automatically available
153
+ # on scopes. Assuming the following setup:
154
+ #
155
+ # class Article < ActiveRecord::Base
156
+ # scope :published, where(:published => true)
157
+ # scope :featured, where(:featured => true)
158
+ #
159
+ # def self.latest_article
160
+ # order('published_at desc').first
161
+ # end
162
+ #
163
+ # def self.titles
164
+ # map(&:title)
165
+ # end
166
+ #
167
+ # end
168
+ #
169
+ # We are able to call the methods like this:
170
+ #
171
+ # Article.published.featured.latest_article
172
+ # Article.featured.titles
173
+
174
+ def scope(name, scope_options = {})
175
+ name = name.to_sym
176
+ valid_scope_name?(name)
177
+ extension = Module.new(&Proc.new) if block_given?
178
+
179
+ scope_proc = lambda do |*args|
180
+ options = scope_options.respond_to?(:call) ? unscoped { scope_options.call(*args) } : scope_options
181
+ options = scoped.apply_finder_options(options) if options.is_a?(Hash)
182
+
183
+ relation = scoped.merge(options)
184
+
185
+ extension ? relation.extending(extension) : relation
186
+ end
187
+
188
+ singleton_class.send(:redefine_method, name, &scope_proc)
189
+ end
190
+
191
+ protected
192
+
193
+ def valid_scope_name?(name)
194
+ if respond_to?(name, true)
195
+ logger.warn "Creating scope :#{name}. " \
196
+ "Overwriting existing method #{self.name}.#{name}."
197
+ end
198
+ end
199
+ end
200
+ end
201
+ end
202
+ end