How safe is overriding an active record class #attributes method?

Hi,

I’m looking at providing computed values (aka not an attribute from a DB column) by default when serializing an active record.

One option we considered is overriding #attributes methods on an active record to return computed values as well.

Something like this:

def attributes
  super.merge("computed_value" => computed_value)
end

Questions:

  • We’re currently rejecting that option but how safe would that be?
  • Is there a proper way to tell an active record to always return a computed value during serialization?

Note: It would be nice to override a configuration instead of creating a new method, as we’re serializing multiple active records from different classes in a loop and would prefer not using :respond_to?

How would overriding the #attributes method impact performance, especially when serializing multiple active records in a loop? Have you tested the overhead caused by this?

@alexb52 You are probably looking for something like attribute :computed_value, :string macro from the ActiveRecord::Attributes::ClassMethods module.