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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With