Skip to content

Commit 6e284f3

Browse files
authored
Merge pull request rails#53345 from tenderlove/init-attributes
Pull attribute initialization in to a function
2 parents 75162bb + 4e003d6 commit 6e284f3

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

activemodel/lib/active_model/dirty.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,12 +247,18 @@ module Dirty
247247

248248
def initialize_dup(other) # :nodoc:
249249
super
250+
@mutations_from_database = nil
251+
end
252+
253+
def init_attributes(other) # :nodoc:
254+
attrs = super
250255
if other.persisted? && self.class.respond_to?(:_default_attributes)
251-
@attributes = self.class._default_attributes.map do |attr|
252-
attr.with_value_from_user(@attributes.fetch_value(attr.name))
256+
self.class._default_attributes.map do |attr|
257+
attr.with_value_from_user(attrs.fetch_value(attr.name))
253258
end
259+
else
260+
attrs
254261
end
255-
@mutations_from_database = nil
256262
end
257263

258264
def as_json(options = {}) # :nodoc:

activerecord/lib/active_record/core.rb

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -525,12 +525,7 @@ def init_with_attributes(attributes, new_record = false) # :nodoc:
525525

526526
##
527527
def initialize_dup(other) # :nodoc:
528-
@attributes = @attributes.deep_dup
529-
if self.class.composite_primary_key?
530-
@primary_key.each { |key| @attributes.reset(key) }
531-
else
532-
@attributes.reset(@primary_key)
533-
end
528+
@attributes = init_attributes(other)
534529

535530
_run_initialize_callbacks
536531

@@ -542,6 +537,18 @@ def initialize_dup(other) # :nodoc:
542537
super
543538
end
544539

540+
def init_attributes(_) # :nodoc:
541+
attrs = @attributes.deep_dup
542+
543+
if self.class.composite_primary_key?
544+
@primary_key.each { |key| attrs.reset(key) }
545+
else
546+
attrs.reset(@primary_key)
547+
end
548+
549+
attrs
550+
end
551+
545552
# Populate +coder+ with attributes about this record that should be
546553
# serialized. The structure of +coder+ defined in this method is
547554
# guaranteed to match the structure of +coder+ passed to the #init_with

0 commit comments

Comments
 (0)