[Braindump]
I stumbled on the code to define an attribute in the model. Since my personal opinion is that default and type logic of an attribute is the responsibility of the model and not of a database column type I was really happy to see the code appear in rails:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attributes.rb#L78
The current implementation of the attribute method requires a mandatory second argument type caster object. Since active record has a very good mechanism of creating a good default type caster based on a database column I suggest to use it for this method. In pseudo monkey patch code:
class MyModel < ActiveRecord::Base
def self.attribute(name, options = {})
type_caster = options.delete(:type) || columns_hash[name.to_s].cast_type
super(name, type_caster, options)
end
attribute :my_number, default: 5 attribute :price_in_cents, type: MoneyType.new end
aka, make the type caster an option, not a required argument and fall back to the default based on the database column type.
Thanks for all the good work!!
Benjamin ter Kuile