module ActiveModel::Type::SerializeCastValue

def self.included(klass)

def self.included(klass)
  klass.include DefaultImplementation unless klass.method_defined?(:serialize_cast_value)
end

def self.serialize(type, value)

def self.serialize(type, value)
  # Using `type.equal?(type.itself_if_...)` is a performant way to also
  # ensure that `type` is not just a DelegateClass instance (e.g.
  # ActiveRecord::Type::Serialized) unintentionally delegating
  # SerializeCastValue methods.
  if type.equal?((type.itself_if_serialize_cast_value_compatible rescue nil))
    type.serialize_cast_value(value)
  else
    type.serialize(value)
  end
end

def initialize(...)

def initialize(...)
  super
  self.class.serialize_cast_value_compatible? # eagerly compute
end

def itself_if_serialize_cast_value_compatible

def itself_if_serialize_cast_value_compatible
  self if self.class.serialize_cast_value_compatible?
end