activerecord 3.1.11 → 3.2.0

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 (106) hide show
  1. data/CHANGELOG.md +6294 -97
  2. data/README.rdoc +2 -2
  3. data/examples/performance.rb +55 -31
  4. data/lib/active_record/aggregations.rb +2 -2
  5. data/lib/active_record/associations/association.rb +2 -42
  6. data/lib/active_record/associations/association_scope.rb +3 -30
  7. data/lib/active_record/associations/builder/association.rb +6 -4
  8. data/lib/active_record/associations/builder/belongs_to.rb +3 -3
  9. data/lib/active_record/associations/builder/collection_association.rb +2 -2
  10. data/lib/active_record/associations/builder/has_many.rb +4 -4
  11. data/lib/active_record/associations/builder/has_one.rb +5 -6
  12. data/lib/active_record/associations/builder/singular_association.rb +3 -16
  13. data/lib/active_record/associations/collection_association.rb +55 -28
  14. data/lib/active_record/associations/collection_proxy.rb +1 -35
  15. data/lib/active_record/associations/has_many_association.rb +5 -1
  16. data/lib/active_record/associations/has_many_through_association.rb +11 -8
  17. data/lib/active_record/associations/join_dependency.rb +1 -1
  18. data/lib/active_record/associations/preloader/association.rb +3 -1
  19. data/lib/active_record/associations.rb +82 -69
  20. data/lib/active_record/attribute_assignment.rb +221 -0
  21. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  22. data/lib/active_record/attribute_methods/dirty.rb +3 -3
  23. data/lib/active_record/attribute_methods/primary_key.rb +62 -25
  24. data/lib/active_record/attribute_methods/read.rb +72 -83
  25. data/lib/active_record/attribute_methods/serialization.rb +93 -0
  26. data/lib/active_record/attribute_methods/time_zone_conversion.rb +9 -14
  27. data/lib/active_record/attribute_methods/write.rb +27 -5
  28. data/lib/active_record/attribute_methods.rb +209 -30
  29. data/lib/active_record/autosave_association.rb +23 -8
  30. data/lib/active_record/base.rb +217 -1709
  31. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +98 -132
  32. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +82 -29
  33. data/lib/active_record/connection_adapters/abstract/database_statements.rb +13 -42
  34. data/lib/active_record/connection_adapters/abstract/query_cache.rb +1 -1
  35. data/lib/active_record/connection_adapters/abstract/quoting.rb +9 -12
  36. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +36 -25
  37. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +43 -22
  38. data/lib/active_record/connection_adapters/abstract_adapter.rb +78 -43
  39. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
  40. data/lib/active_record/connection_adapters/column.rb +2 -2
  41. data/lib/active_record/connection_adapters/mysql2_adapter.rb +138 -578
  42. data/lib/active_record/connection_adapters/mysql_adapter.rb +86 -658
  43. data/lib/active_record/connection_adapters/postgresql_adapter.rb +144 -94
  44. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  45. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +2 -6
  46. data/lib/active_record/connection_adapters/sqlite_adapter.rb +43 -22
  47. data/lib/active_record/counter_cache.rb +4 -3
  48. data/lib/active_record/dynamic_matchers.rb +79 -0
  49. data/lib/active_record/errors.rb +11 -1
  50. data/lib/active_record/explain.rb +83 -0
  51. data/lib/active_record/explain_subscriber.rb +21 -0
  52. data/lib/active_record/fixtures/file.rb +65 -0
  53. data/lib/active_record/fixtures.rb +31 -76
  54. data/lib/active_record/identity_map.rb +4 -11
  55. data/lib/active_record/inheritance.rb +167 -0
  56. data/lib/active_record/integration.rb +49 -0
  57. data/lib/active_record/locking/optimistic.rb +30 -25
  58. data/lib/active_record/locking/pessimistic.rb +23 -1
  59. data/lib/active_record/log_subscriber.rb +3 -3
  60. data/lib/active_record/migration/command_recorder.rb +8 -8
  61. data/lib/active_record/migration.rb +47 -30
  62. data/lib/active_record/model_schema.rb +366 -0
  63. data/lib/active_record/nested_attributes.rb +3 -2
  64. data/lib/active_record/persistence.rb +51 -9
  65. data/lib/active_record/querying.rb +58 -0
  66. data/lib/active_record/railtie.rb +24 -28
  67. data/lib/active_record/railties/controller_runtime.rb +3 -1
  68. data/lib/active_record/railties/databases.rake +134 -77
  69. data/lib/active_record/railties/jdbcmysql_error.rb +1 -1
  70. data/lib/active_record/readonly_attributes.rb +26 -0
  71. data/lib/active_record/reflection.rb +7 -15
  72. data/lib/active_record/relation/batches.rb +5 -2
  73. data/lib/active_record/relation/calculations.rb +27 -6
  74. data/lib/active_record/relation/delegation.rb +49 -0
  75. data/lib/active_record/relation/finder_methods.rb +6 -5
  76. data/lib/active_record/relation/predicate_builder.rb +12 -19
  77. data/lib/active_record/relation/query_methods.rb +76 -10
  78. data/lib/active_record/relation/spawn_methods.rb +11 -2
  79. data/lib/active_record/relation.rb +77 -34
  80. data/lib/active_record/result.rb +1 -1
  81. data/lib/active_record/sanitization.rb +194 -0
  82. data/lib/active_record/schema_dumper.rb +5 -2
  83. data/lib/active_record/scoping/default.rb +142 -0
  84. data/lib/active_record/scoping/named.rb +202 -0
  85. data/lib/active_record/scoping.rb +152 -0
  86. data/lib/active_record/serialization.rb +1 -43
  87. data/lib/active_record/serializers/xml_serializer.rb +2 -44
  88. data/lib/active_record/session_store.rb +15 -15
  89. data/lib/active_record/store.rb +50 -0
  90. data/lib/active_record/test_case.rb +11 -7
  91. data/lib/active_record/timestamp.rb +16 -3
  92. data/lib/active_record/transactions.rb +5 -5
  93. data/lib/active_record/translation.rb +22 -0
  94. data/lib/active_record/validations/associated.rb +5 -4
  95. data/lib/active_record/validations/uniqueness.rb +4 -4
  96. data/lib/active_record/validations.rb +1 -1
  97. data/lib/active_record/version.rb +2 -2
  98. data/lib/active_record.rb +28 -2
  99. data/lib/rails/generators/active_record/migration/migration_generator.rb +1 -1
  100. data/lib/rails/generators/active_record/migration/templates/migration.rb +9 -3
  101. data/lib/rails/generators/active_record/model/model_generator.rb +5 -1
  102. data/lib/rails/generators/active_record/model/templates/migration.rb +3 -5
  103. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +1 -5
  104. metadata +50 -40
  105. checksums.yaml +0 -7
  106. data/lib/active_record/named_scope.rb +0 -200
@@ -0,0 +1,194 @@
1
+ require 'active_support/concern'
2
+
3
+ module ActiveRecord
4
+ module Sanitization
5
+ extend ActiveSupport::Concern
6
+
7
+ module ClassMethods
8
+ def quote_value(value, column = nil) #:nodoc:
9
+ connection.quote(value,column)
10
+ end
11
+
12
+ # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
13
+ def sanitize(object) #:nodoc:
14
+ connection.quote(object)
15
+ end
16
+
17
+ protected
18
+
19
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
20
+ # them into a valid SQL fragment for a WHERE clause.
21
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
22
+ # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
23
+ # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
24
+ def sanitize_sql_for_conditions(condition, table_name = self.table_name)
25
+ return nil if condition.blank?
26
+
27
+ case condition
28
+ when Array; sanitize_sql_array(condition)
29
+ when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
30
+ else condition
31
+ end
32
+ end
33
+ alias_method :sanitize_sql, :sanitize_sql_for_conditions
34
+
35
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
36
+ # them into a valid SQL fragment for a SET clause.
37
+ # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
38
+ def sanitize_sql_for_assignment(assignments)
39
+ case assignments
40
+ when Array; sanitize_sql_array(assignments)
41
+ when Hash; sanitize_sql_hash_for_assignment(assignments)
42
+ else assignments
43
+ end
44
+ end
45
+
46
+ # Accepts a hash of SQL conditions and replaces those attributes
47
+ # that correspond to a +composed_of+ relationship with their expanded
48
+ # aggregate attribute values.
49
+ # Given:
50
+ # class Person < ActiveRecord::Base
51
+ # composed_of :address, :class_name => "Address",
52
+ # :mapping => [%w(address_street street), %w(address_city city)]
53
+ # end
54
+ # Then:
55
+ # { :address => Address.new("813 abc st.", "chicago") }
56
+ # # => { :address_street => "813 abc st.", :address_city => "chicago" }
57
+ def expand_hash_conditions_for_aggregates(attrs)
58
+ expanded_attrs = {}
59
+ attrs.each do |attr, value|
60
+ unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil?
61
+ mapping = aggregate_mapping(aggregation)
62
+ mapping.each do |field_attr, aggregate_attr|
63
+ if mapping.size == 1 && !value.respond_to?(aggregate_attr)
64
+ expanded_attrs[field_attr] = value
65
+ else
66
+ expanded_attrs[field_attr] = value.send(aggregate_attr)
67
+ end
68
+ end
69
+ else
70
+ expanded_attrs[attr] = value
71
+ end
72
+ end
73
+ expanded_attrs
74
+ end
75
+
76
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
77
+ # { :name => "foo'bar", :group_id => 4 }
78
+ # # => "name='foo''bar' and group_id= 4"
79
+ # { :status => nil, :group_id => [1,2,3] }
80
+ # # => "status IS NULL and group_id IN (1,2,3)"
81
+ # { :age => 13..18 }
82
+ # # => "age BETWEEN 13 AND 18"
83
+ # { 'other_records.id' => 7 }
84
+ # # => "`other_records`.`id` = 7"
85
+ # { :other_records => { :id => 7 } }
86
+ # # => "`other_records`.`id` = 7"
87
+ # And for value objects on a composed_of relationship:
88
+ # { :address => Address.new("123 abc st.", "chicago") }
89
+ # # => "address_street='123 abc st.' and address_city='chicago'"
90
+ def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
91
+ attrs = expand_hash_conditions_for_aggregates(attrs)
92
+
93
+ table = Arel::Table.new(table_name).alias(default_table_name)
94
+ PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
95
+ connection.visitor.accept b
96
+ }.join(' AND ')
97
+ end
98
+ alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
99
+
100
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
101
+ # { :status => nil, :group_id => 1 }
102
+ # # => "status = NULL , group_id = 1"
103
+ def sanitize_sql_hash_for_assignment(attrs)
104
+ attrs.map do |attr, value|
105
+ "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
106
+ end.join(', ')
107
+ end
108
+
109
+ # Accepts an array of conditions. The array has each value
110
+ # sanitized and interpolated into the SQL statement.
111
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
112
+ def sanitize_sql_array(ary)
113
+ statement, *values = ary
114
+ if values.first.is_a?(Hash) && statement =~ /:\w+/
115
+ replace_named_bind_variables(statement, values.first)
116
+ elsif statement.include?('?')
117
+ replace_bind_variables(statement, values)
118
+ elsif statement.blank?
119
+ statement
120
+ else
121
+ statement % values.collect { |value| connection.quote_string(value.to_s) }
122
+ end
123
+ end
124
+
125
+ alias_method :sanitize_conditions, :sanitize_sql
126
+
127
+ def replace_bind_variables(statement, values) #:nodoc:
128
+ raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
129
+ bound = values.dup
130
+ c = connection
131
+ statement.gsub('?') { quote_bound_value(bound.shift, c) }
132
+ end
133
+
134
+ def replace_named_bind_variables(statement, bind_vars) #:nodoc:
135
+ statement.gsub(/(:?):([a-zA-Z]\w*)/) do
136
+ if $1 == ':' # skip postgresql casts
137
+ $& # return the whole match
138
+ elsif bind_vars.include?(match = $2.to_sym)
139
+ quote_bound_value(bind_vars[match])
140
+ else
141
+ raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
142
+ end
143
+ end
144
+ end
145
+
146
+ def expand_range_bind_variables(bind_vars) #:nodoc:
147
+ expanded = []
148
+
149
+ bind_vars.each do |var|
150
+ next if var.is_a?(Hash)
151
+
152
+ if var.is_a?(Range)
153
+ expanded << var.first
154
+ expanded << var.last
155
+ else
156
+ expanded << var
157
+ end
158
+ end
159
+
160
+ expanded
161
+ end
162
+
163
+ def quote_bound_value(value, c = connection) #:nodoc:
164
+ if value.respond_to?(:map) && !value.acts_like?(:string)
165
+ if value.respond_to?(:empty?) && value.empty?
166
+ c.quote(nil)
167
+ else
168
+ value.map { |v| c.quote(v) }.join(',')
169
+ end
170
+ else
171
+ c.quote(value)
172
+ end
173
+ end
174
+
175
+ def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
176
+ unless expected == provided
177
+ raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
178
+ end
179
+ end
180
+ end
181
+
182
+ # TODO: Deprecate this
183
+ def quoted_id #:nodoc:
184
+ quote_value(id, column_for_attribute(self.class.primary_key))
185
+ end
186
+
187
+ private
188
+
189
+ # Quote strings appropriately for SQL statements.
190
+ def quote_value(value, column = nil)
191
+ self.class.connection.quote(value, column)
192
+ end
193
+ end
194
+ end
@@ -40,7 +40,7 @@ module ActiveRecord
40
40
  def header(stream)
41
41
  define_params = @version ? ":version => #{@version}" : ""
42
42
 
43
- if stream.respond_to?(:external_encoding) && stream.external_encoding
43
+ if stream.respond_to?(:external_encoding)
44
44
  stream.puts "# encoding: #{stream.external_encoding.name}"
45
45
  end
46
46
 
@@ -110,7 +110,7 @@ HEADER
110
110
  spec = {}
111
111
  spec[:name] = column.name.inspect
112
112
 
113
- # AR has an optimisation which handles zero-scale decimals as integers. This
113
+ # AR has an optimization which handles zero-scale decimals as integers. This
114
114
  # code ensures that the dumper still dumps the column as a decimal.
115
115
  spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) }
116
116
  'decimal'
@@ -190,6 +190,9 @@ HEADER
190
190
  index_lengths = (index.lengths || []).compact
191
191
  statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?
192
192
 
193
+ index_orders = (index.orders || {})
194
+ statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty?
195
+
193
196
  ' ' + statement_parts.join(', ')
194
197
  end
195
198
 
@@ -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