views:

482

answers:

2

Hey,

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?

+1  A: 

A callback is more short lived: You pass it into a function to be called once. It's part of the API in that you usually can't call the function without also passing a callback. This concept is tightly coupled with what the function does. Usually, you can only pass a single callback..

Example: Running a thread and giving a callback that is called when the thread terminates.

An observer lives longer and it can be attached/detached at any time. There can be many observers for the same thing and they can have different lifetimes.

Example: Showing values from a model in a UI and updating the model from user input.

Aaron Digulla
+3  A: 

You can use observers as a means of decoupling or distribution of responsibility. In the basic sense - if your model code gets too messy start to think about using observers for some unessential behavior. The real power (at least as I see it) of observers lies in their ability to serve as a connection point between your models and some other subsystem whose functionality is used by all (or some) of the other classes. Let's say you decide to add an IM notification to your application - say you want to be notified about some (or all) of the CRUD actions of some (or all) of the models in your system. In this case using observers would be ideal - your notification subsystem will stay perfectly separated from your business logic and your models won't be cluttered with behavior which is not of their business. Another good use case for observers would be an auditing subsystem.

Milan Novota