ActiveRecord model attribute definition with type caster and default

[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

This is not currently public API, the final API will likely support default values when it is made public in the future.

Nice!

Any news on this topic? The current master branch code still does not support inferring the type as a default when it is obvious from the database column, aka:

class StoreListing < ActiveRecord::Base
attribute :my_string, :string, default: “new default”
end

Should be:

class StoreListing < ActiveRecord::Base
attribute :my_string, default: “new default”
end

since the database column type is a string type.

I disagree, just set a database default if that's your use case