In plain java I’d use:
public User(String name, String email) {
this.name = name;
this.email = f(email);
this.admin = false;
}
However, I couldn’t find a simple standard way to do in rails (3.2.3), with ActiveRecords.
1. override initialize
def initialize(attributes = {}, options = {})
@name = attributes[:name]
@email = f(attributes[:email])
@admin = false
end
but it might be missed when creating a record from the DB
2. using the after_initialize callback
by overriding it:
def after_initialize(attributes = {}, options = {})
...
end
or with the macro:
after_initialize : my_own_little_init
def my_own_little_init(attributes = {}, options = {})
...
end
but there may be some deprecation issues.
There are some other links in SO, but they may be out-of-date.
So, what’s the correct/standard method to use?
Your default values should be defined in your Schema when they will apply to ALL records. So
Here, every new Post will have false for published. If you want default values at the object level, it’s best to use Factory style implementations: