2

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?
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
dadads
  • 201
  • 1
  • 8

1 Answers1

1

According to Design Patterns book this is most appropriate for the Observer pattern. With and Observer, your after_update/save logic is decoupled from your model. Hard to tell from your example, but if you are updating other models from your callbacks then you are polluting your User model with knowledge of other model. Thus, and Observer should step in to take care of that.

Also, you can disable observers in Rails, thus making your unit tests faster where you don't care about "callbacks" getting triggered.

gylaz
  • 13,221
  • 8
  • 52
  • 58