This post originated from an RSS feed registered with Ruby Buzz
by Robby Russell.
Original Post: Observers Big and Small
Feed Title: Robby on Rails
Feed URL: http://feeds.feedburner.com/RobbyOnRails
Feed Description: Ruby on Rails development, consulting, and hosting from the trenches...
My colleague, Gary, keeps a stack of Ruby and Rails books on his desk and was implementing an Observer into a client project. It appears that the Agile Web Development with Rails book is still encouraging people to do the following in order to load an Observer.
# app/models/flower_observer.rb
class FlowerObserver < ActiveRecord::Observer
observe Flower
def after_create(model)
# model.do_something!
end
end
# controller(s)
class FlowerController < ApplicationController
observer :flower_observer
end
What is wrong with this approach?
Well, in order for your Observer to be used, the model(s) callbacks that it is observing need to be triggered through a controller. If you end up writing any scheduled rake tasks, your observer will not be called. In my opinion, the controller shouldn’t know this much about the model. In fact, the model doesn’t even really know about it’s observer… so why should a controller?