activerecord 3.1.9 → 3.2.12

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 (112) hide show
  1. checksums.yaml +6 -6
  2. data/CHANGELOG.md +317 -336
  3. data/README.rdoc +3 -3
  4. data/examples/performance.rb +20 -1
  5. data/lib/active_record/aggregations.rb +1 -1
  6. data/lib/active_record/associations/alias_tracker.rb +3 -6
  7. data/lib/active_record/associations/association.rb +3 -42
  8. data/lib/active_record/associations/association_scope.rb +3 -15
  9. data/lib/active_record/associations/builder/association.rb +6 -4
  10. data/lib/active_record/associations/builder/belongs_to.rb +3 -3
  11. data/lib/active_record/associations/builder/collection_association.rb +2 -2
  12. data/lib/active_record/associations/builder/has_many.rb +4 -4
  13. data/lib/active_record/associations/builder/has_one.rb +5 -6
  14. data/lib/active_record/associations/builder/singular_association.rb +3 -16
  15. data/lib/active_record/associations/collection_association.rb +64 -31
  16. data/lib/active_record/associations/collection_proxy.rb +2 -37
  17. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +1 -0
  18. data/lib/active_record/associations/has_many_association.rb +5 -1
  19. data/lib/active_record/associations/has_many_through_association.rb +28 -9
  20. data/lib/active_record/associations/has_one_association.rb +15 -13
  21. data/lib/active_record/associations/join_dependency.rb +2 -2
  22. data/lib/active_record/associations/preloader.rb +14 -10
  23. data/lib/active_record/associations/through_association.rb +7 -3
  24. data/lib/active_record/associations.rb +92 -76
  25. data/lib/active_record/attribute_assignment.rb +221 -0
  26. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  27. data/lib/active_record/attribute_methods/dirty.rb +21 -11
  28. data/lib/active_record/attribute_methods/primary_key.rb +62 -25
  29. data/lib/active_record/attribute_methods/read.rb +73 -83
  30. data/lib/active_record/attribute_methods/serialization.rb +102 -0
  31. data/lib/active_record/attribute_methods/time_zone_conversion.rb +23 -17
  32. data/lib/active_record/attribute_methods/write.rb +31 -6
  33. data/lib/active_record/attribute_methods.rb +231 -30
  34. data/lib/active_record/autosave_association.rb +43 -22
  35. data/lib/active_record/base.rb +227 -1708
  36. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +150 -148
  37. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +85 -29
  38. data/lib/active_record/connection_adapters/abstract/database_statements.rb +6 -33
  39. data/lib/active_record/connection_adapters/abstract/query_cache.rb +10 -2
  40. data/lib/active_record/connection_adapters/abstract/quoting.rb +15 -6
  41. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +37 -26
  42. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +48 -19
  43. data/lib/active_record/connection_adapters/abstract_adapter.rb +77 -42
  44. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +674 -0
  45. data/lib/active_record/connection_adapters/column.rb +37 -11
  46. data/lib/active_record/connection_adapters/mysql2_adapter.rb +129 -581
  47. data/lib/active_record/connection_adapters/mysql_adapter.rb +137 -696
  48. data/lib/active_record/connection_adapters/postgresql_adapter.rb +184 -86
  49. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  50. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +2 -6
  51. data/lib/active_record/connection_adapters/sqlite_adapter.rb +55 -32
  52. data/lib/active_record/counter_cache.rb +9 -4
  53. data/lib/active_record/dynamic_finder_match.rb +12 -0
  54. data/lib/active_record/dynamic_matchers.rb +84 -0
  55. data/lib/active_record/errors.rb +11 -1
  56. data/lib/active_record/explain.rb +85 -0
  57. data/lib/active_record/explain_subscriber.rb +25 -0
  58. data/lib/active_record/fixtures/file.rb +65 -0
  59. data/lib/active_record/fixtures.rb +56 -85
  60. data/lib/active_record/identity_map.rb +3 -4
  61. data/lib/active_record/inheritance.rb +174 -0
  62. data/lib/active_record/integration.rb +49 -0
  63. data/lib/active_record/locking/optimistic.rb +30 -25
  64. data/lib/active_record/locking/pessimistic.rb +23 -1
  65. data/lib/active_record/log_subscriber.rb +3 -3
  66. data/lib/active_record/migration/command_recorder.rb +8 -8
  67. data/lib/active_record/migration.rb +68 -35
  68. data/lib/active_record/model_schema.rb +366 -0
  69. data/lib/active_record/nested_attributes.rb +3 -2
  70. data/lib/active_record/persistence.rb +57 -11
  71. data/lib/active_record/querying.rb +58 -0
  72. data/lib/active_record/railtie.rb +31 -29
  73. data/lib/active_record/railties/controller_runtime.rb +3 -1
  74. data/lib/active_record/railties/databases.rake +191 -110
  75. data/lib/active_record/railties/jdbcmysql_error.rb +1 -1
  76. data/lib/active_record/readonly_attributes.rb +26 -0
  77. data/lib/active_record/reflection.rb +7 -15
  78. data/lib/active_record/relation/batches.rb +5 -2
  79. data/lib/active_record/relation/calculations.rb +47 -15
  80. data/lib/active_record/relation/delegation.rb +49 -0
  81. data/lib/active_record/relation/finder_methods.rb +9 -7
  82. data/lib/active_record/relation/predicate_builder.rb +18 -7
  83. data/lib/active_record/relation/query_methods.rb +75 -9
  84. data/lib/active_record/relation/spawn_methods.rb +11 -2
  85. data/lib/active_record/relation.rb +78 -32
  86. data/lib/active_record/result.rb +1 -1
  87. data/lib/active_record/sanitization.rb +194 -0
  88. data/lib/active_record/schema_dumper.rb +12 -5
  89. data/lib/active_record/scoping/default.rb +142 -0
  90. data/lib/active_record/scoping/named.rb +202 -0
  91. data/lib/active_record/scoping.rb +152 -0
  92. data/lib/active_record/serialization.rb +1 -43
  93. data/lib/active_record/serializers/xml_serializer.rb +4 -45
  94. data/lib/active_record/session_store.rb +17 -15
  95. data/lib/active_record/store.rb +52 -0
  96. data/lib/active_record/test_case.rb +11 -7
  97. data/lib/active_record/timestamp.rb +17 -3
  98. data/lib/active_record/transactions.rb +27 -6
  99. data/lib/active_record/translation.rb +22 -0
  100. data/lib/active_record/validations/associated.rb +5 -4
  101. data/lib/active_record/validations/uniqueness.rb +7 -7
  102. data/lib/active_record/validations.rb +1 -1
  103. data/lib/active_record/version.rb +2 -2
  104. data/lib/active_record.rb +38 -3
  105. data/lib/rails/generators/active_record/migration/migration_generator.rb +1 -1
  106. data/lib/rails/generators/active_record/migration/templates/migration.rb +12 -3
  107. data/lib/rails/generators/active_record/model/model_generator.rb +9 -1
  108. data/lib/rails/generators/active_record/model/templates/migration.rb +3 -5
  109. data/lib/rails/generators/active_record/model/templates/model.rb +5 -0
  110. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +1 -5
  111. metadata +30 -10
  112. data/lib/active_record/named_scope.rb +0 -200
@@ -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
@@ -10,50 +10,8 @@ module ActiveRecord #:nodoc:
10
10
  options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
11
11
  options[:except] |= Array.wrap(self.class.inheritance_column)
12
12
 
13
- hash = super(options)
14
-
15
- serializable_add_includes(options) do |association, records, opts|
16
- hash[association] = records.is_a?(Enumerable) ?
17
- records.map { |r| r.serializable_hash(opts) } :
18
- records.serializable_hash(opts)
19
- end
20
-
21
- hash
13
+ super(options)
22
14
  end
23
-
24
- private
25
- # Add associations specified via the <tt>:include</tt> option.
26
- #
27
- # Expects a block that takes as arguments:
28
- # +association+ - name of the association
29
- # +records+ - the association record(s) to be serialized
30
- # +opts+ - options for the association records
31
- def serializable_add_includes(options = {})
32
- return unless include_associations = options.delete(:include)
33
-
34
- base_only_or_except = { :except => options[:except],
35
- :only => options[:only] }
36
-
37
- include_has_options = include_associations.is_a?(Hash)
38
- associations = include_has_options ? include_associations.keys : Array.wrap(include_associations)
39
-
40
- associations.each do |association|
41
- records = case self.class.reflect_on_association(association).macro
42
- when :has_many, :has_and_belongs_to_many
43
- send(association).to_a
44
- when :has_one, :belongs_to
45
- send(association)
46
- end
47
-
48
- if records
49
- association_options = include_has_options ? include_associations[association] : base_only_or_except
50
- opts = options.merge(association_options)
51
- yield(association, records, opts)
52
- end
53
- end
54
-
55
- options[:include] = include_associations
56
- end
57
15
  end
58
16
  end
59
17
 
@@ -75,7 +75,7 @@ module ActiveRecord #:nodoc:
75
75
  # </firm>
76
76
  #
77
77
  # Additionally, the record being serialized will be passed to a Proc's second
78
- # parameter. This allows for ad hoc additions to the resultant document that
78
+ # parameter. This allows for ad hoc additions to the resultant document that
79
79
  # incorporate the context of the record being serialized. And by leveraging the
80
80
  # closure created by a Proc, to_xml can be used to add elements that normally fall
81
81
  # outside of the scope of the model -- for example, generating and appending URLs
@@ -163,8 +163,9 @@ module ActiveRecord #:nodoc:
163
163
  #
164
164
  # class IHaveMyOwnXML < ActiveRecord::Base
165
165
  # def to_xml(options = {})
166
+ # require 'builder'
166
167
  # options[:indent] ||= 2
167
- # xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
168
+ # xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
168
169
  # xml.instruct! unless options[:skip_instruct]
169
170
  # xml.level_one do
170
171
  # xml.tag!(:second_level, 'content')
@@ -179,49 +180,7 @@ module ActiveRecord #:nodoc:
179
180
  class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
180
181
  def initialize(*args)
181
182
  super
182
- options[:except] |= Array.wrap(@serializable.class.inheritance_column)
183
- end
184
-
185
- def add_extra_behavior
186
- add_includes
187
- end
188
-
189
- def add_includes
190
- procs = options.delete(:procs)
191
- @serializable.send(:serializable_add_includes, options) do |association, records, opts|
192
- add_associations(association, records, opts)
193
- end
194
- options[:procs] = procs
195
- end
196
-
197
- # TODO This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
198
- def add_associations(association, records, opts)
199
- association_name = association.to_s.singularize
200
- merged_options = options.merge(opts).merge!(:root => association_name, :skip_instruct => true)
201
-
202
- if records.is_a?(Enumerable)
203
- tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
204
- type = options[:skip_types] ? { } : {:type => "array"}
205
-
206
- if records.empty?
207
- @builder.tag!(tag, type)
208
- else
209
- @builder.tag!(tag, type) do
210
- records.each do |record|
211
- if options[:skip_types]
212
- record_type = {}
213
- else
214
- record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
215
- record_type = {:type => record_class}
216
- end
217
-
218
- record.to_xml merged_options.merge(record_type)
219
- end
220
- end
221
- end
222
- elsif record = @serializable.send(association)
223
- record.to_xml(merged_options)
224
- end
183
+ options[:except] = Array.wrap(options[:except]) | Array.wrap(@serializable.class.inheritance_column)
225
184
  end
226
185
 
227
186
  class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
@@ -1,7 +1,9 @@
1
+ require 'action_dispatch/middleware/session/abstract_store'
2
+
1
3
  module ActiveRecord
2
4
  # = Active Record Session Store
3
5
  #
4
- # A session store backed by an Active Record class. A default class is
6
+ # A session store backed by an Active Record class. A default class is
5
7
  # provided, but any object duck-typing to an Active Record Session class
6
8
  # with text +session_id+ and +data+ attributes is sufficient.
7
9
  #
@@ -23,7 +25,7 @@ module ActiveRecord
23
25
  # ActiveRecord::SessionStore::Session.data_column_name = 'legacy_session_data'
24
26
  #
25
27
  # Note that setting the primary key to the +session_id+ frees you from
26
- # having a separate +id+ column if you don't want it. However, you must
28
+ # having a separate +id+ column if you don't want it. However, you must
27
29
  # set <tt>session.model.id = session.session_id</tt> by hand! A before filter
28
30
  # on ApplicationController is a good place.
29
31
  #
@@ -46,25 +48,25 @@ module ActiveRecord
46
48
  # save
47
49
  # destroy
48
50
  #
49
- # The example SqlBypass class is a generic SQL session store. You may
51
+ # The example SqlBypass class is a generic SQL session store. You may
50
52
  # use it as a basis for high-performance database-specific stores.
51
53
  class SessionStore < ActionDispatch::Session::AbstractStore
52
54
  module ClassMethods # :nodoc:
53
55
  def marshal(data)
54
- ActiveSupport::Base64.encode64(Marshal.dump(data)) if data
56
+ ::Base64.encode64(Marshal.dump(data)) if data
55
57
  end
56
58
 
57
59
  def unmarshal(data)
58
- Marshal.load(ActiveSupport::Base64.decode64(data)) if data
60
+ Marshal.load(::Base64.decode64(data)) if data
59
61
  end
60
62
 
61
63
  def drop_table!
62
- connection_pool.clear_table_cache!(table_name)
64
+ connection.schema_cache.clear_table_cache!(table_name)
63
65
  connection.drop_table table_name
64
66
  end
65
67
 
66
68
  def create_table!
67
- connection_pool.clear_table_cache!(table_name)
69
+ connection.schema_cache.clear_table_cache!(table_name)
68
70
  connection.create_table(table_name) do |t|
69
71
  t.string session_id_column, :limit => 255
70
72
  t.text data_column_name
@@ -79,7 +81,7 @@ module ActiveRecord
79
81
 
80
82
  ##
81
83
  # :singleton-method:
82
- # Customizable data column name. Defaults to 'data'.
84
+ # Customizable data column name. Defaults to 'data'.
83
85
  cattr_accessor :data_column_name
84
86
  self.data_column_name = 'data'
85
87
 
@@ -161,22 +163,22 @@ module ActiveRecord
161
163
  end
162
164
 
163
165
  # A barebones session store which duck-types with the default session
164
- # store but bypasses Active Record and issues SQL directly. This is
166
+ # store but bypasses Active Record and issues SQL directly. This is
165
167
  # an example session model class meant as a basis for your own classes.
166
168
  #
167
169
  # The database connection, table name, and session id and data columns
168
- # are configurable class attributes. Marshaling and unmarshaling
169
- # are implemented as class methods that you may override. By default,
170
+ # are configurable class attributes. Marshaling and unmarshaling
171
+ # are implemented as class methods that you may override. By default,
170
172
  # marshaling data is
171
173
  #
172
- # ActiveSupport::Base64.encode64(Marshal.dump(data))
174
+ # ::Base64.encode64(Marshal.dump(data))
173
175
  #
174
176
  # and unmarshaling data is
175
177
  #
176
- # Marshal.load(ActiveSupport::Base64.decode64(data))
178
+ # Marshal.load(::Base64.decode64(data))
177
179
  #
178
180
  # This marshaling behavior is intended to store the widest range of
179
- # binary session data in a +text+ column. For higher performance,
181
+ # binary session data in a +text+ column. For higher performance,
180
182
  # store in a +blob+ column instead and forgo the Base64 encoding.
181
183
  class SqlBypass
182
184
  extend ClassMethods
@@ -292,7 +294,7 @@ module ActiveRecord
292
294
  end
293
295
  end
294
296
 
295
- # The class used for session storage. Defaults to
297
+ # The class used for session storage. Defaults to
296
298
  # ActiveRecord::SessionStore::Session
297
299
  cattr_accessor :session_class
298
300
  self.session_class = Session
@@ -0,0 +1,52 @@
1
+ module ActiveRecord
2
+ # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
3
+ # It's like a simple key/value store backed into your record when you don't care about being able to
4
+ # query that store outside the context of a single record.
5
+ #
6
+ # You can then declare accessors to this store that are then accessible just like any other attribute
7
+ # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
8
+ # already built around just accessing attributes on the model.
9
+ #
10
+ # Make sure that you declare the database column used for the serialized store as a text, so there's
11
+ # plenty of room.
12
+ #
13
+ # Examples:
14
+ #
15
+ # class User < ActiveRecord::Base
16
+ # store :settings, accessors: [ :color, :homepage ]
17
+ # end
18
+ #
19
+ # u = User.new(color: 'black', homepage: '37signals.com')
20
+ # u.color # Accessor stored attribute
21
+ # u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
22
+ #
23
+ # # Add additional accessors to an existing store through store_accessor
24
+ # class SuperUser < User
25
+ # store_accessor :settings, :privileges, :servants
26
+ # end
27
+ module Store
28
+ extend ActiveSupport::Concern
29
+
30
+ module ClassMethods
31
+ def store(store_attribute, options = {})
32
+ serialize store_attribute, Hash
33
+ store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
34
+ end
35
+
36
+ def store_accessor(store_attribute, *keys)
37
+ Array(keys).flatten.each do |key|
38
+ define_method("#{key}=") do |value|
39
+ send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash)
40
+ send(store_attribute)[key] = value
41
+ send("#{store_attribute}_will_change!")
42
+ end
43
+
44
+ define_method(key) do
45
+ send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash)
46
+ send(store_attribute)[key]
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -13,7 +13,7 @@ module ActiveRecord
13
13
  ActiveRecord::IdentityMap.clear
14
14
  end
15
15
 
16
- # Backport skip to Ruby 1.8. test/unit doesn't support it, so just
16
+ # Backport skip to Ruby 1.8. test/unit doesn't support it, so just
17
17
  # make it a noop.
18
18
  unless instance_methods.map(&:to_s).include?("skip")
19
19
  def skip(message)
@@ -31,26 +31,30 @@ module ActiveRecord
31
31
  end
32
32
 
33
33
  def assert_sql(*patterns_to_match)
34
- $queries_executed = []
34
+ ActiveRecord::SQLCounter.log = []
35
35
  yield
36
- $queries_executed
36
+ ActiveRecord::SQLCounter.log
37
37
  ensure
38
38
  failed_patterns = []
39
39
  patterns_to_match.each do |pattern|
40
- failed_patterns << pattern unless $queries_executed.any?{ |sql| pattern === sql }
40
+ failed_patterns << pattern unless ActiveRecord::SQLCounter.log.any?{ |sql| pattern === sql }
41
41
  end
42
- assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
42
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}"
43
43
  end
44
44
 
45
45
  def assert_queries(num = 1)
46
- $queries_executed = []
46
+ ActiveRecord::SQLCounter.log = []
47
47
  yield
48
48
  ensure
49
- assert_equal num, $queries_executed.size, "#{$queries_executed.size} instead of #{num} queries were executed.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
49
+ assert_equal num, ActiveRecord::SQLCounter.log.size, "#{ActiveRecord::SQLCounter.log.size} instead of #{num} queries were executed.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}"
50
50
  end
51
51
 
52
52
  def assert_no_queries(&block)
53
+ prev_ignored_sql = ActiveRecord::SQLCounter.ignored_sql
54
+ ActiveRecord::SQLCounter.ignored_sql = []
53
55
  assert_queries(0, &block)
56
+ ensure
57
+ ActiveRecord::SQLCounter.ignored_sql = prev_ignored_sql
54
58
  end
55
59
 
56
60
  def with_kcode(kcode)
@@ -33,10 +33,15 @@ module ActiveRecord
33
33
  extend ActiveSupport::Concern
34
34
 
35
35
  included do
36
- class_attribute :record_timestamps, :instance_writer => false
36
+ class_attribute :record_timestamps
37
37
  self.record_timestamps = true
38
38
  end
39
39
 
40
+ def initialize_dup(other)
41
+ clear_timestamp_attributes
42
+ super
43
+ end
44
+
40
45
  private
41
46
 
42
47
  def create #:nodoc:
@@ -44,7 +49,9 @@ module ActiveRecord
44
49
  current_time = current_time_from_proper_timezone
45
50
 
46
51
  all_timestamp_attributes.each do |column|
47
- write_attribute(column.to_s, current_time) if respond_to?(column) && self.send(column).nil?
52
+ if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
53
+ write_attribute(column.to_s, current_time)
54
+ end
48
55
  end
49
56
  end
50
57
 
@@ -95,6 +102,13 @@ module ActiveRecord
95
102
  def current_time_from_proper_timezone #:nodoc:
96
103
  self.class.default_timezone == :utc ? Time.now.utc : Time.now
97
104
  end
105
+
106
+ # Clear attributes and changed_attributes
107
+ def clear_timestamp_attributes
108
+ all_timestamp_attributes_in_model.each do |attribute_name|
109
+ self[attribute_name] = nil
110
+ changed_attributes.delete(attribute_name)
111
+ end
112
+ end
98
113
  end
99
114
  end
100
-
@@ -208,6 +208,21 @@ module ActiveRecord
208
208
  connection.transaction(options, &block)
209
209
  end
210
210
 
211
+ # This callback is called after a record has been created, updated, or destroyed.
212
+ #
213
+ # You can specify that the callback should only be fired by a certain action with
214
+ # the +:on+ option:
215
+ #
216
+ # after_commit :do_foo, :on => :create
217
+ # after_commit :do_bar, :on => :update
218
+ # after_commit :do_baz, :on => :destroy
219
+ #
220
+ # Also, to have the callback fired on create and update, but not on destroy:
221
+ #
222
+ # after_commit :do_zoo, :if => :persisted?
223
+ #
224
+ # Note that transactional fixtures do not play well with this feature. Please
225
+ # use the +test_after_commit+ gem to have these hooks fired in tests.
211
226
  def after_commit(*args, &block)
212
227
  options = args.last
213
228
  if options.is_a?(Hash) && options[:on]
@@ -217,6 +232,9 @@ module ActiveRecord
217
232
  set_callback(:commit, :after, *args, &block)
218
233
  end
219
234
 
235
+ # This callback is called after a create, update, or destroy are rolled back.
236
+ #
237
+ # Please check the documentation of +after_commit+ for options.
220
238
  def after_rollback(*args, &block)
221
239
  options = args.last
222
240
  if options.is_a?(Hash) && options[:on]
@@ -301,7 +319,7 @@ module ActiveRecord
301
319
  protected
302
320
 
303
321
  # Save the new record state and id of a record so it can be restored later if a transaction fails.
304
- def remember_transaction_record_state #:nodoc
322
+ def remember_transaction_record_state #:nodoc:
305
323
  @_start_transaction_state ||= {}
306
324
  @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
307
325
  unless @_start_transaction_state.include?(:new_record)
@@ -311,10 +329,11 @@ module ActiveRecord
311
329
  @_start_transaction_state[:destroyed] = @destroyed
312
330
  end
313
331
  @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
332
+ @_start_transaction_state[:frozen?] = @attributes.frozen?
314
333
  end
315
334
 
316
335
  # Clear the new record state and id of a record.
317
- def clear_transaction_record_state #:nodoc
336
+ def clear_transaction_record_state #:nodoc:
318
337
  if defined?(@_start_transaction_state)
319
338
  @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
320
339
  remove_instance_variable(:@_start_transaction_state) if @_start_transaction_state[:level] < 1
@@ -322,11 +341,12 @@ module ActiveRecord
322
341
  end
323
342
 
324
343
  # Restore the new record state and id of a record that was previously saved by a call to save_record_state.
325
- def restore_transaction_record_state(force = false) #:nodoc
344
+ def restore_transaction_record_state(force = false) #:nodoc:
326
345
  if defined?(@_start_transaction_state)
327
346
  @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
328
- if @_start_transaction_state[:level] < 1
347
+ if @_start_transaction_state[:level] < 1 || force
329
348
  restore_state = remove_instance_variable(:@_start_transaction_state)
349
+ was_frozen = restore_state[:frozen?]
330
350
  @attributes = @attributes.dup if @attributes.frozen?
331
351
  @new_record = restore_state[:new_record]
332
352
  @destroyed = restore_state[:destroyed]
@@ -336,17 +356,18 @@ module ActiveRecord
336
356
  @attributes.delete(self.class.primary_key)
337
357
  @attributes_cache.delete(self.class.primary_key)
338
358
  end
359
+ @attributes.freeze if was_frozen
339
360
  end
340
361
  end
341
362
  end
342
363
 
343
364
  # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
344
- def transaction_record_state(state) #:nodoc
365
+ def transaction_record_state(state) #:nodoc:
345
366
  @_start_transaction_state[state] if defined?(@_start_transaction_state)
346
367
  end
347
368
 
348
369
  # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
349
- def transaction_include_action?(action) #:nodoc
370
+ def transaction_include_action?(action) #:nodoc:
350
371
  case action
351
372
  when :create
352
373
  transaction_record_state(:new_record)
@@ -0,0 +1,22 @@
1
+ module ActiveRecord
2
+ module Translation
3
+ include ActiveModel::Translation
4
+
5
+ # Set the lookup ancestors for ActiveModel.
6
+ def lookup_ancestors #:nodoc:
7
+ klass = self
8
+ classes = [klass]
9
+ return classes if klass == ActiveRecord::Base
10
+
11
+ while klass != klass.base_class
12
+ classes << klass = klass.superclass
13
+ end
14
+ classes
15
+ end
16
+
17
+ # Set the i18n scope to overwrite ActiveModel.
18
+ def i18n_scope #:nodoc:
19
+ :activerecord
20
+ end
21
+ end
22
+ end
@@ -2,8 +2,9 @@ module ActiveRecord
2
2
  module Validations
3
3
  class AssociatedValidator < ActiveModel::EachValidator
4
4
  def validate_each(record, attribute, value)
5
- return if (value.is_a?(Array) ? value : [value]).collect{ |r| r.nil? || r.valid? }.all?
6
- record.errors.add(attribute, :invalid, options.merge(:value => value))
5
+ if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any?
6
+ record.errors.add(attribute, :invalid, options.merge(:value => value))
7
+ end
7
8
  end
8
9
  end
9
10
 
@@ -29,10 +30,10 @@ module ActiveRecord
29
30
  # validation contexts by default (+nil+), other options are <tt>:create</tt>
30
31
  # and <tt>:update</tt>.
31
32
  # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
32
- # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
33
+ # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
33
34
  # method, proc or string should return or evaluate to a true or false value.
34
35
  # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
35
- # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
36
+ # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
36
37
  # method, proc or string should return or evaluate to a true or false value.
37
38
  def validates_associated(*attr_names)
38
39
  validates_with AssociatedValidator, _merge_attributes(attr_names)