diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 3636fd7f8f..250d926bed 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -69,14 +69,7 @@ module ActiveRecord Coders::YAMLColumn.new(attr_name, class_name_or_coder) end - attr_name = attr_name.to_s - type, options = attributes_to_define_after_schema_loads[attr_name] - - attribute(attr_name) do |cast_type| - if type && !type.is_a?(Proc) - cast_type = _lookup_cast_type(attr_name, type, options) - end - + decorate_attribute_type(attr_name.to_s) do |cast_type| if type_incompatible_with_serialize?(cast_type, class_name_or_coder) raise ColumnNotSerializableError.new(attr_name, cast_type) end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index f30b2acc3f..cb0d388b09 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -270,6 +270,18 @@ module ActiveRecord _default_attributes[name] = default_attribute end + def decorate_attribute_type(attr_name, **default) + type, options = attributes_to_define_after_schema_loads[attr_name] + + attribute(attr_name, **default) do |cast_type| + if type && !type.is_a?(Proc) + cast_type = _lookup_cast_type(attr_name, type, options) + end + + yield cast_type + end + end + def _lookup_cast_type(name, type, options) case type when Symbol diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index fca471f63c..f7aebc5ecb 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -183,13 +183,8 @@ module ActiveRecord detect_enum_conflict!(name, "#{name}=") attr = attribute_alias?(name) ? attribute_alias(name) : name - type, options = attributes_to_define_after_schema_loads[attr] - - attribute(attr, **default) do |subtype| - if type && !type.is_a?(Proc) - subtype = _lookup_cast_type(attr, type, options) - end + decorate_attribute_type(attr, **default) do |subtype| EnumType.new(attr, enum_values, subtype) end