Observers or callbacks?

Why use an Observer for a single model rather than using a callback in
the ActiveRecord object? They seem like they work identically. Is
there a difference I’m missing?

For example, these seem like they would do the same thing:

class User < ActiveRecord::Base
after_create :send_welcome

  def send_welcome


class UserObserver < ActiveRecord::Observer
def after_create(user)

– TW

Hi tekwiz,

This is excerpt is from Agile Web D. with Rails:

Callbacks are a fine technique, but they can sometimes result in a
model class
taking on responsibilities that aren’t really related to the nature of
the model.
For example, on page 385 we created a callback that generated a log
when an order was created. That functionality isn’t really part of the
Order class—we put it there because that’s where the callback
Active Record observers overcome that limitation. An observer
links itself into a model class, registering itself for callbacks as
if it were part
of the model but without requiring any changes in the model itself.

Thanks elioncho! I understand that it is a best practice to separate
certain functionality out of models into observers.

I guess I should clarify my question… Is there any technical
reason to use observers instead of callbacks or visa versa.

– TW

I’d really like to know the answer to that too!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs