Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observers vs. Callbacks

i thought about using observers or callbacks. What and when you should use an observer?

F.e. you could do following:

# User-model class User << AR   after_create :send_greeting!    def send_greeting!     UserNotifier.deliver_greeting_message(self)   end  end  #observer class UserNotifier << AR   def greeting_message(user)   ...   end end 

or you could create an observer and let it watch when users becomes created...

What dou you recommened?

like image 892
BvuRVKyUVlViVIc7 Avatar asked Oct 07 '09 13:10

BvuRVKyUVlViVIc7


People also ask

What are observers in Rails?

Observers register themselves in the model class they observe, since it is the class that notifies them of events when they occur. As a side-effect, when an observer is loaded its corresponding model class is loaded. Up to (and including) Rails 2.0.

What are callbacks in rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.


1 Answers

One really important distinction to keep in mind, which is related to Milan Novota's answer, is that callbacks on an ActiveRecord have the ability to cancel the action being called and all subsequent callbacks, where as observers do not.

class Model < ActiveRecord::Base   before_update :disallow_bob    def disallow_bob   return false if model.name == "bob"   end end  class ModelObserver < ActiveRecord::Observer   def before_update(model)     return false if model.name == "mary"   end end  m = Model.create(:name => "whatever")  m.update_attributes(:name => "bob") => false -- name will still be "whatever" in database  m.update_attributes(:name => "mary") => true -- name will be "mary" in database 

Observers may only observe, they may not intervene.

like image 195
Michael Johnston Avatar answered Sep 20 '22 23:09

Michael Johnston