I would modify the code as follows:
class Product < ActiveRecord::Base ... def set_default_value(state = merchant.state) if state self.foo = some_value else self.foo = some_other_value end end end
Then change your caller to:
product = merchant.products.build(:state => merchant.state)
In addition, I found that after_initialize callbacks will be slow. So another option is to move the logic to the constructor for the product.
product = merchant.products.build(:foo => merchant.state ? some_value : some_other_value)
It also eliminates the violation of the law of Demeter from the code (i.e. the Product does not need to know / care about what the seller’s condition is).
Jason noble
source share