activerecord 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (162) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1024 -543
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +20 -29
  5. data/examples/performance.rb +1 -1
  6. data/lib/active_record.rb +55 -44
  7. data/lib/active_record/aggregations.rb +40 -34
  8. data/lib/active_record/associations.rb +204 -276
  9. data/lib/active_record/associations/alias_tracker.rb +1 -1
  10. data/lib/active_record/associations/association.rb +30 -35
  11. data/lib/active_record/associations/association_scope.rb +40 -40
  12. data/lib/active_record/associations/belongs_to_association.rb +15 -2
  13. data/lib/active_record/associations/builder/association.rb +81 -28
  14. data/lib/active_record/associations/builder/belongs_to.rb +35 -57
  15. data/lib/active_record/associations/builder/collection_association.rb +54 -40
  16. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +23 -41
  17. data/lib/active_record/associations/builder/has_many.rb +8 -64
  18. data/lib/active_record/associations/builder/has_one.rb +13 -50
  19. data/lib/active_record/associations/builder/singular_association.rb +13 -13
  20. data/lib/active_record/associations/collection_association.rb +92 -88
  21. data/lib/active_record/associations/collection_proxy.rb +913 -63
  22. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +12 -10
  23. data/lib/active_record/associations/has_many_association.rb +35 -9
  24. data/lib/active_record/associations/has_many_through_association.rb +24 -14
  25. data/lib/active_record/associations/has_one_association.rb +33 -13
  26. data/lib/active_record/associations/has_one_through_association.rb +1 -1
  27. data/lib/active_record/associations/join_dependency.rb +2 -2
  28. data/lib/active_record/associations/join_dependency/join_association.rb +17 -22
  29. data/lib/active_record/associations/join_dependency/join_part.rb +1 -1
  30. data/lib/active_record/associations/join_helper.rb +1 -11
  31. data/lib/active_record/associations/preloader.rb +14 -17
  32. data/lib/active_record/associations/preloader/association.rb +29 -33
  33. data/lib/active_record/associations/preloader/collection_association.rb +1 -1
  34. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +1 -1
  35. data/lib/active_record/associations/preloader/has_many_through.rb +1 -1
  36. data/lib/active_record/associations/preloader/has_one.rb +1 -1
  37. data/lib/active_record/associations/preloader/through_association.rb +13 -17
  38. data/lib/active_record/associations/singular_association.rb +11 -11
  39. data/lib/active_record/associations/through_association.rb +2 -2
  40. data/lib/active_record/attribute_assignment.rb +133 -153
  41. data/lib/active_record/attribute_methods.rb +196 -93
  42. data/lib/active_record/attribute_methods/before_type_cast.rb +44 -5
  43. data/lib/active_record/attribute_methods/dirty.rb +31 -28
  44. data/lib/active_record/attribute_methods/primary_key.rb +38 -30
  45. data/lib/active_record/attribute_methods/query.rb +5 -4
  46. data/lib/active_record/attribute_methods/read.rb +62 -91
  47. data/lib/active_record/attribute_methods/serialization.rb +97 -66
  48. data/lib/active_record/attribute_methods/time_zone_conversion.rb +39 -45
  49. data/lib/active_record/attribute_methods/write.rb +32 -39
  50. data/lib/active_record/autosave_association.rb +56 -70
  51. data/lib/active_record/base.rb +53 -450
  52. data/lib/active_record/callbacks.rb +53 -18
  53. data/lib/active_record/coders/yaml_column.rb +11 -9
  54. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +353 -197
  55. data/lib/active_record/connection_adapters/abstract/database_limits.rb +9 -0
  56. data/lib/active_record/connection_adapters/abstract/database_statements.rb +130 -131
  57. data/lib/active_record/connection_adapters/abstract/query_cache.rb +24 -19
  58. data/lib/active_record/connection_adapters/abstract/quoting.rb +23 -3
  59. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +101 -91
  60. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +59 -0
  61. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +225 -96
  62. data/lib/active_record/connection_adapters/abstract/transaction.rb +203 -0
  63. data/lib/active_record/connection_adapters/abstract_adapter.rb +99 -46
  64. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +114 -36
  65. data/lib/active_record/connection_adapters/column.rb +46 -24
  66. data/lib/active_record/connection_adapters/connection_specification.rb +96 -0
  67. data/lib/active_record/connection_adapters/mysql2_adapter.rb +16 -32
  68. data/lib/active_record/connection_adapters/mysql_adapter.rb +181 -64
  69. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +97 -0
  70. data/lib/active_record/connection_adapters/postgresql/cast.rb +132 -0
  71. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +242 -0
  72. data/lib/active_record/connection_adapters/postgresql/oid.rb +347 -0
  73. data/lib/active_record/connection_adapters/postgresql/quoting.rb +158 -0
  74. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +30 -0
  75. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +448 -0
  76. data/lib/active_record/connection_adapters/postgresql_adapter.rb +454 -885
  77. data/lib/active_record/connection_adapters/schema_cache.rb +48 -16
  78. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +574 -13
  79. data/lib/active_record/connection_handling.rb +98 -0
  80. data/lib/active_record/core.rb +428 -0
  81. data/lib/active_record/counter_cache.rb +106 -108
  82. data/lib/active_record/dynamic_matchers.rb +110 -63
  83. data/lib/active_record/errors.rb +25 -8
  84. data/lib/active_record/explain.rb +8 -58
  85. data/lib/active_record/explain_subscriber.rb +6 -3
  86. data/lib/active_record/fixture_set/file.rb +56 -0
  87. data/lib/active_record/fixtures.rb +146 -148
  88. data/lib/active_record/inheritance.rb +77 -59
  89. data/lib/active_record/integration.rb +5 -5
  90. data/lib/active_record/locale/en.yml +8 -1
  91. data/lib/active_record/locking/optimistic.rb +38 -42
  92. data/lib/active_record/locking/pessimistic.rb +4 -4
  93. data/lib/active_record/log_subscriber.rb +19 -9
  94. data/lib/active_record/migration.rb +318 -153
  95. data/lib/active_record/migration/command_recorder.rb +90 -31
  96. data/lib/active_record/migration/join_table.rb +15 -0
  97. data/lib/active_record/model_schema.rb +69 -92
  98. data/lib/active_record/nested_attributes.rb +113 -148
  99. data/lib/active_record/null_relation.rb +65 -0
  100. data/lib/active_record/persistence.rb +188 -97
  101. data/lib/active_record/query_cache.rb +18 -36
  102. data/lib/active_record/querying.rb +19 -15
  103. data/lib/active_record/railtie.rb +91 -36
  104. data/lib/active_record/railties/console_sandbox.rb +0 -2
  105. data/lib/active_record/railties/controller_runtime.rb +2 -2
  106. data/lib/active_record/railties/databases.rake +90 -309
  107. data/lib/active_record/railties/jdbcmysql_error.rb +1 -1
  108. data/lib/active_record/readonly_attributes.rb +7 -3
  109. data/lib/active_record/reflection.rb +72 -56
  110. data/lib/active_record/relation.rb +241 -157
  111. data/lib/active_record/relation/batches.rb +25 -22
  112. data/lib/active_record/relation/calculations.rb +143 -121
  113. data/lib/active_record/relation/delegation.rb +96 -18
  114. data/lib/active_record/relation/finder_methods.rb +117 -183
  115. data/lib/active_record/relation/merger.rb +133 -0
  116. data/lib/active_record/relation/predicate_builder.rb +90 -42
  117. data/lib/active_record/relation/query_methods.rb +666 -136
  118. data/lib/active_record/relation/spawn_methods.rb +43 -150
  119. data/lib/active_record/result.rb +33 -6
  120. data/lib/active_record/sanitization.rb +24 -50
  121. data/lib/active_record/schema.rb +19 -12
  122. data/lib/active_record/schema_dumper.rb +31 -39
  123. data/lib/active_record/schema_migration.rb +36 -0
  124. data/lib/active_record/scoping.rb +0 -124
  125. data/lib/active_record/scoping/default.rb +48 -45
  126. data/lib/active_record/scoping/named.rb +74 -103
  127. data/lib/active_record/serialization.rb +6 -2
  128. data/lib/active_record/serializers/xml_serializer.rb +9 -15
  129. data/lib/active_record/store.rb +119 -15
  130. data/lib/active_record/tasks/database_tasks.rb +158 -0
  131. data/lib/active_record/tasks/mysql_database_tasks.rb +138 -0
  132. data/lib/active_record/tasks/postgresql_database_tasks.rb +90 -0
  133. data/lib/active_record/tasks/sqlite_database_tasks.rb +51 -0
  134. data/lib/active_record/test_case.rb +61 -38
  135. data/lib/active_record/timestamp.rb +8 -9
  136. data/lib/active_record/transactions.rb +65 -51
  137. data/lib/active_record/validations.rb +17 -15
  138. data/lib/active_record/validations/associated.rb +20 -14
  139. data/lib/active_record/validations/presence.rb +65 -0
  140. data/lib/active_record/validations/uniqueness.rb +93 -52
  141. data/lib/active_record/version.rb +4 -4
  142. data/lib/rails/generators/active_record.rb +3 -5
  143. data/lib/rails/generators/active_record/migration/migration_generator.rb +37 -7
  144. data/lib/rails/generators/active_record/migration/templates/migration.rb +20 -15
  145. data/lib/rails/generators/active_record/model/model_generator.rb +4 -3
  146. data/lib/rails/generators/active_record/model/templates/model.rb +1 -6
  147. data/lib/rails/generators/active_record/model/templates/module.rb +1 -1
  148. metadata +53 -46
  149. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +0 -32
  150. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +0 -191
  151. data/lib/active_record/connection_adapters/sqlite_adapter.rb +0 -583
  152. data/lib/active_record/dynamic_finder_match.rb +0 -68
  153. data/lib/active_record/dynamic_scope_match.rb +0 -23
  154. data/lib/active_record/fixtures/file.rb +0 -65
  155. data/lib/active_record/identity_map.rb +0 -162
  156. data/lib/active_record/observer.rb +0 -121
  157. data/lib/active_record/session_store.rb +0 -360
  158. data/lib/rails/generators/active_record/migration.rb +0 -15
  159. data/lib/rails/generators/active_record/observer/observer_generator.rb +0 -15
  160. data/lib/rails/generators/active_record/observer/templates/observer.rb +0 -4
  161. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +0 -25
  162. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +0 -12
@@ -0,0 +1,98 @@
1
+ module ActiveRecord
2
+ module ConnectionHandling
3
+ # Establishes the connection to the database. Accepts a hash as input where
4
+ # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
5
+ # example for regular databases (MySQL, Postgresql, etc):
6
+ #
7
+ # ActiveRecord::Base.establish_connection(
8
+ # adapter: "mysql",
9
+ # host: "localhost",
10
+ # username: "myuser",
11
+ # password: "mypass",
12
+ # database: "somedatabase"
13
+ # )
14
+ #
15
+ # Example for SQLite database:
16
+ #
17
+ # ActiveRecord::Base.establish_connection(
18
+ # adapter: "sqlite",
19
+ # database: "path/to/dbfile"
20
+ # )
21
+ #
22
+ # Also accepts keys as strings (for parsing from YAML for example):
23
+ #
24
+ # ActiveRecord::Base.establish_connection(
25
+ # "adapter" => "sqlite",
26
+ # "database" => "path/to/dbfile"
27
+ # )
28
+ #
29
+ # Or a URL:
30
+ #
31
+ # ActiveRecord::Base.establish_connection(
32
+ # "postgres://myuser:mypass@localhost/somedatabase"
33
+ # )
34
+ #
35
+ # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
36
+ # may be returned on an error.
37
+ def establish_connection(spec = ENV["DATABASE_URL"])
38
+ resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations
39
+ spec = resolver.spec
40
+
41
+ unless respond_to?(spec.adapter_method)
42
+ raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
43
+ end
44
+
45
+ remove_connection
46
+ connection_handler.establish_connection self, spec
47
+ end
48
+
49
+ # Returns the connection currently associated with the class. This can
50
+ # also be used to "borrow" the connection to do database work unrelated
51
+ # to any of the specific Active Records.
52
+ def connection
53
+ retrieve_connection
54
+ end
55
+
56
+ def connection_id
57
+ Thread.current['ActiveRecord::Base.connection_id']
58
+ end
59
+
60
+ def connection_id=(connection_id)
61
+ Thread.current['ActiveRecord::Base.connection_id'] = connection_id
62
+ end
63
+
64
+ # Returns the configuration of the associated connection as a hash:
65
+ #
66
+ # ActiveRecord::Base.connection_config
67
+ # # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
68
+ #
69
+ # Please use only for reading.
70
+ def connection_config
71
+ connection_pool.spec.config
72
+ end
73
+
74
+ def connection_pool
75
+ connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
76
+ end
77
+
78
+ def retrieve_connection
79
+ connection_handler.retrieve_connection(self)
80
+ end
81
+
82
+ # Returns true if Active Record is connected.
83
+ def connected?
84
+ connection_handler.connected?(self)
85
+ end
86
+
87
+ def remove_connection(klass = self)
88
+ connection_handler.remove_connection(klass)
89
+ end
90
+
91
+ def clear_cache! # :nodoc:
92
+ connection.schema_cache.clear!
93
+ end
94
+
95
+ delegate :clear_active_connections!, :clear_reloadable_connections!,
96
+ :clear_all_connections!, :to => :connection_handler
97
+ end
98
+ end
@@ -0,0 +1,428 @@
1
+ require 'active_support/core_ext/hash/indifferent_access'
2
+ require 'active_support/core_ext/object/duplicable'
3
+ require 'thread'
4
+
5
+ module ActiveRecord
6
+ module Core
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ ##
11
+ # :singleton-method:
12
+ #
13
+ # Accepts a logger conforming to the interface of Log4r which is then
14
+ # passed on to any new database connections made and which can be
15
+ # retrieved on both a class and instance level by calling +logger+.
16
+ mattr_accessor :logger, instance_writer: false
17
+
18
+ ##
19
+ # :singleton-method:
20
+ # Contains the database configuration - as is typically stored in config/database.yml -
21
+ # as a Hash.
22
+ #
23
+ # For example, the following database.yml...
24
+ #
25
+ # development:
26
+ # adapter: sqlite3
27
+ # database: db/development.sqlite3
28
+ #
29
+ # production:
30
+ # adapter: sqlite3
31
+ # database: db/production.sqlite3
32
+ #
33
+ # ...would result in ActiveRecord::Base.configurations to look like this:
34
+ #
35
+ # {
36
+ # 'development' => {
37
+ # 'adapter' => 'sqlite3',
38
+ # 'database' => 'db/development.sqlite3'
39
+ # },
40
+ # 'production' => {
41
+ # 'adapter' => 'sqlite3',
42
+ # 'database' => 'db/production.sqlite3'
43
+ # }
44
+ # }
45
+ mattr_accessor :configurations, instance_writer: false
46
+ self.configurations = {}
47
+
48
+ ##
49
+ # :singleton-method:
50
+ # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
51
+ # dates and times from the database. This is set to :utc by default.
52
+ mattr_accessor :default_timezone, instance_writer: false
53
+ self.default_timezone = :utc
54
+
55
+ ##
56
+ # :singleton-method:
57
+ # Specifies the format to use when dumping the database schema with Rails'
58
+ # Rakefile. If :sql, the schema is dumped as (potentially database-
59
+ # specific) SQL statements. If :ruby, the schema is dumped as an
60
+ # ActiveRecord::Schema file which can be loaded into any database that
61
+ # supports migrations. Use :ruby if you want to have different database
62
+ # adapters for, e.g., your development and test environments.
63
+ mattr_accessor :schema_format, instance_writer: false
64
+ self.schema_format = :ruby
65
+
66
+ ##
67
+ # :singleton-method:
68
+ # Specify whether or not to use timestamps for migration versions
69
+ mattr_accessor :timestamped_migrations, instance_writer: false
70
+ self.timestamped_migrations = true
71
+
72
+ class_attribute :connection_handler, instance_writer: false
73
+ self.connection_handler = ConnectionAdapters::ConnectionHandler.new
74
+ end
75
+
76
+ module ClassMethods
77
+ def inherited(child_class) #:nodoc:
78
+ child_class.initialize_generated_modules
79
+ super
80
+ end
81
+
82
+ def initialize_generated_modules
83
+ @attribute_methods_mutex = Mutex.new
84
+
85
+ # force attribute methods to be higher in inheritance hierarchy than other generated methods
86
+ generated_attribute_methods.const_set(:AttrNames, Module.new {
87
+ def self.const_missing(name)
88
+ const_set(name, [name.to_s.sub(/ATTR_/, '')].pack('h*').freeze)
89
+ end
90
+ })
91
+
92
+ generated_feature_methods
93
+ end
94
+
95
+ def generated_feature_methods
96
+ @generated_feature_methods ||= begin
97
+ mod = const_set(:GeneratedFeatureMethods, Module.new)
98
+ include mod
99
+ mod
100
+ end
101
+ end
102
+
103
+ # Returns a string like 'Post(id:integer, title:string, body:text)'
104
+ def inspect
105
+ if self == Base
106
+ super
107
+ elsif abstract_class?
108
+ "#{super}(abstract)"
109
+ elsif table_exists?
110
+ attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
111
+ "#{super}(#{attr_list})"
112
+ else
113
+ "#{super}(Table doesn't exist)"
114
+ end
115
+ end
116
+
117
+ # Overwrite the default class equality method to provide support for association proxies.
118
+ def ===(object)
119
+ object.is_a?(self)
120
+ end
121
+
122
+ # Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
123
+ #
124
+ # class Post < ActiveRecord::Base
125
+ # scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
126
+ # end
127
+ def arel_table
128
+ @arel_table ||= Arel::Table.new(table_name, arel_engine)
129
+ end
130
+
131
+ # Returns the Arel engine.
132
+ def arel_engine
133
+ @arel_engine ||= begin
134
+ if Base == self || connection_handler.retrieve_connection_pool(self)
135
+ self
136
+ else
137
+ superclass.arel_engine
138
+ end
139
+ end
140
+ end
141
+
142
+ private
143
+
144
+ def relation #:nodoc:
145
+ relation = Relation.new(self, arel_table)
146
+
147
+ if finder_needs_type_condition?
148
+ relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
149
+ else
150
+ relation
151
+ end
152
+ end
153
+ end
154
+
155
+ # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
156
+ # attributes but not yet saved (pass a hash with key names matching the associated table column names).
157
+ # In both instances, valid attribute keys are determined by the column names of the associated table --
158
+ # hence you can't have attributes that aren't part of the table columns.
159
+ #
160
+ # ==== Example:
161
+ # # Instantiates a single new object
162
+ # User.new(first_name: 'Jamie')
163
+ def initialize(attributes = nil)
164
+ defaults = self.class.column_defaults.dup
165
+ defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
166
+
167
+ @attributes = self.class.initialize_attributes(defaults)
168
+ @columns_hash = self.class.column_types.dup
169
+
170
+ init_internals
171
+ ensure_proper_type
172
+ populate_with_current_scope_attributes
173
+
174
+ assign_attributes(attributes) if attributes
175
+
176
+ yield self if block_given?
177
+ run_callbacks :initialize unless _initialize_callbacks.empty?
178
+ end
179
+
180
+ # Initialize an empty model object from +coder+. +coder+ must contain
181
+ # the attributes necessary for initializing an empty model object. For
182
+ # example:
183
+ #
184
+ # class Post < ActiveRecord::Base
185
+ # end
186
+ #
187
+ # post = Post.allocate
188
+ # post.init_with('attributes' => { 'title' => 'hello world' })
189
+ # post.title # => 'hello world'
190
+ def init_with(coder)
191
+ @attributes = self.class.initialize_attributes(coder['attributes'])
192
+ @columns_hash = self.class.column_types.merge(coder['column_types'] || {})
193
+
194
+ init_internals
195
+
196
+ @new_record = false
197
+
198
+ run_callbacks :find
199
+ run_callbacks :initialize
200
+
201
+ self
202
+ end
203
+
204
+ ##
205
+ # :method: clone
206
+ # Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
207
+ # That means that modifying attributes of the clone will modify the original, since they will both point to the
208
+ # same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
209
+ #
210
+ # user = User.first
211
+ # new_user = user.clone
212
+ # user.name # => "Bob"
213
+ # new_user.name = "Joe"
214
+ # user.name # => "Joe"
215
+ #
216
+ # user.object_id == new_user.object_id # => false
217
+ # user.name.object_id == new_user.name.object_id # => true
218
+ #
219
+ # user.name.object_id == user.dup.name.object_id # => false
220
+
221
+ ##
222
+ # :method: dup
223
+ # Duped objects have no id assigned and are treated as new records. Note
224
+ # that this is a "shallow" copy as it copies the object's attributes
225
+ # only, not its associations. The extent of a "deep" copy is application
226
+ # specific and is therefore left to the application to implement according
227
+ # to its need.
228
+ # The dup method does not preserve the timestamps (created|updated)_(at|on).
229
+
230
+ ##
231
+ def initialize_dup(other) # :nodoc:
232
+ cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
233
+ self.class.initialize_attributes(cloned_attributes, :serialized => false)
234
+
235
+ @attributes = cloned_attributes
236
+ @attributes[self.class.primary_key] = nil
237
+
238
+ run_callbacks(:initialize) unless _initialize_callbacks.empty?
239
+
240
+ @changed_attributes = {}
241
+ self.class.column_defaults.each do |attr, orig_value|
242
+ @changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
243
+ end
244
+
245
+ @aggregation_cache = {}
246
+ @association_cache = {}
247
+ @attributes_cache = {}
248
+
249
+ @new_record = true
250
+
251
+ ensure_proper_type
252
+ super
253
+ end
254
+
255
+ # Populate +coder+ with attributes about this record that should be
256
+ # serialized. The structure of +coder+ defined in this method is
257
+ # guaranteed to match the structure of +coder+ passed to the +init_with+
258
+ # method.
259
+ #
260
+ # Example:
261
+ #
262
+ # class Post < ActiveRecord::Base
263
+ # end
264
+ # coder = {}
265
+ # Post.new.encode_with(coder)
266
+ # coder # => {"attributes" => {"id" => nil, ... }}
267
+ def encode_with(coder)
268
+ coder['attributes'] = attributes
269
+ end
270
+
271
+ # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
272
+ # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
273
+ #
274
+ # Note that new records are different from any other record by definition, unless the
275
+ # other record is the receiver itself. Besides, if you fetch existing records with
276
+ # +select+ and leave the ID out, you're on your own, this predicate will return false.
277
+ #
278
+ # Note also that destroying a record preserves its ID in the model instance, so deleted
279
+ # models are still comparable.
280
+ def ==(comparison_object)
281
+ super ||
282
+ comparison_object.instance_of?(self.class) &&
283
+ id.present? &&
284
+ comparison_object.id == id
285
+ end
286
+ alias :eql? :==
287
+
288
+ # Delegates to id in order to allow two records of the same type and id to work with something like:
289
+ # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
290
+ def hash
291
+ id.hash
292
+ end
293
+
294
+ # Freeze the attributes hash such that associations are still accessible, even on destroyed records.
295
+ def freeze
296
+ @attributes.freeze
297
+ self
298
+ end
299
+
300
+ # Returns +true+ if the attributes hash has been frozen.
301
+ def frozen?
302
+ @attributes.frozen?
303
+ end
304
+
305
+ # Allows sort on objects
306
+ def <=>(other_object)
307
+ if other_object.is_a?(self.class)
308
+ self.to_key <=> other_object.to_key
309
+ end
310
+ end
311
+
312
+ # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
313
+ # attributes will be marked as read only since they cannot be saved.
314
+ def readonly?
315
+ @readonly
316
+ end
317
+
318
+ # Marks this record as read only.
319
+ def readonly!
320
+ @readonly = true
321
+ end
322
+
323
+ # Returns the connection currently associated with the class. This can
324
+ # also be used to "borrow" the connection to do database work that isn't
325
+ # easily done without going straight to SQL.
326
+ def connection
327
+ self.class.connection
328
+ end
329
+
330
+ # Returns the contents of the record as a nicely formatted string.
331
+ def inspect
332
+ inspection = if @attributes
333
+ self.class.column_names.collect { |name|
334
+ if has_attribute?(name)
335
+ "#{name}: #{attribute_for_inspect(name)}"
336
+ end
337
+ }.compact.join(", ")
338
+ else
339
+ "not initialized"
340
+ end
341
+ "#<#{self.class} #{inspection}>"
342
+ end
343
+
344
+ # Returns a hash of the given methods with their names as keys and returned values as values.
345
+ def slice(*methods)
346
+ Hash[methods.map { |method| [method, public_send(method)] }].with_indifferent_access
347
+ end
348
+
349
+ def set_transaction_state(state) # :nodoc:
350
+ @transaction_state = state
351
+ end
352
+
353
+ def has_transactional_callbacks? # :nodoc:
354
+ !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_create_callbacks.empty?
355
+ end
356
+
357
+ private
358
+
359
+ # Updates the attributes on this particular ActiveRecord object so that
360
+ # if it is associated with a transaction, then the state of the AR object
361
+ # will be updated to reflect the current state of the transaction
362
+ #
363
+ # The @transaction_state variable stores the states of the associated
364
+ # transaction. This relies on the fact that a transaction can only be in
365
+ # one rollback or commit (otherwise a list of states would be required)
366
+ # Each AR object inside of a transaction carries that transaction's
367
+ # TransactionState.
368
+ #
369
+ # This method checks to see if the ActiveRecord object's state reflects
370
+ # the TransactionState, and rolls back or commits the ActiveRecord object
371
+ # as appropriate.
372
+ #
373
+ # Since ActiveRecord objects can be inside multiple transactions, this
374
+ # method recursively goes through the parent of the TransactionState and
375
+ # checks if the ActiveRecord object reflects the state of the object.
376
+ def sync_with_transaction_state
377
+ update_attributes_from_transaction_state(@transaction_state, 0)
378
+ end
379
+
380
+ def update_attributes_from_transaction_state(transaction_state, depth)
381
+ if transaction_state && !has_transactional_callbacks?
382
+ unless @reflects_state[depth]
383
+ if transaction_state.committed?
384
+ committed!
385
+ elsif transaction_state.rolledback?
386
+ rolledback!
387
+ end
388
+ @reflects_state[depth] = true
389
+ end
390
+
391
+ if transaction_state.parent && !@reflects_state[depth+1]
392
+ update_attributes_from_transaction_state(transaction_state.parent, depth+1)
393
+ end
394
+ end
395
+ end
396
+
397
+ # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
398
+ # of the array, and then rescues from the possible NoMethodError. If those elements are
399
+ # ActiveRecord::Base's, then this triggers the various method_missing's that we have,
400
+ # which significantly impacts upon performance.
401
+ #
402
+ # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
403
+ #
404
+ # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
405
+ def to_ary # :nodoc:
406
+ nil
407
+ end
408
+
409
+ def init_internals
410
+ pk = self.class.primary_key
411
+ @attributes[pk] = nil unless @attributes.key?(pk)
412
+
413
+ @aggregation_cache = {}
414
+ @association_cache = {}
415
+ @attributes_cache = {}
416
+ @previously_changed = {}
417
+ @changed_attributes = {}
418
+ @readonly = false
419
+ @destroyed = false
420
+ @marked_for_destruction = false
421
+ @new_record = true
422
+ @txn = nil
423
+ @_start_transaction_state = {}
424
+ @transaction_state = nil
425
+ @reflects_state = [false]
426
+ end
427
+ end
428
+ end