I am developing a system where ActiveRecord entities and fields need to be kept consistent at all times. Quite often, certain fields are derived from other fields and need to be kept up to date at all times. Sometimes, this may even happen across entities.
For example:
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name
attr_protected :name
# I need to keep 'name' up to date at all times
after_update do
name = self.first_name + ' ' + self.last_name
true
end
end
The philosophical question here is whether or not I should implement this type of behaviour (and hundreds of similar ones) in a callback or inside an observer. I can think of a few reasons to do both below:
Callbacks
- Behaviour definitions are more easily accessible (you know where to look by just looking at the model definition)
- Maintaining consistency between fields/entities is not an auxiliary concern, but rather an intricate part of the entity's behaviour. Keeping data consistent, in fact, is (implicitly) a first-class requirement for any entity.
Observers
- As system behaviour eventually gets more complex, models tend to be more lightweight (not bloated with hundreds of callback methods)
- Maintaining consistency between fields/entities is an auxiliary concern, unrelated to the model's main responsibility; thus, it should be factored out into an external observer
Can someone with more experience please enlighten me?
- Are there any specific considerations I haven't looked into?
- What is your guideline in terms of deciding what belongs in callbacks versus observers?