Read my latest article: Announcing RailsDeveloper (posted Wed, 01 Sep 2010 17:01:00 GMT)

Observers Big and Small

Posted by Robby Russell Fri, 27 Apr 2007 18:15:00 GMT

41 comments Latest by Gucci Wed, 11 Aug 2010 02:48:34 GMT

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?

This was actually changed a long time ago (I previously blogged about a different solution here) and the Rails docs for ActiveRecord::Observer are currently correct.

Observers in the Environment

If you open up a recent version of config/environment.rb, you notice in the comments the following.


  # Activate observers that should always be running
  # config.active_record.observers = :cacher, :garbage_collector

Take a moment to go ahead and specify which observer(s) you’d like to load into your Rails environment.

config.active_record.observers = :flower_observer

Then you can remove your observer calls in all your controllers, because that’s not where you should be defining them.

Also, if you’re not using Observers yet, I’d really encourage you to consider reading up on them and giving them a try.

Subscribe to my RSS feed Enjoying the content? Be sure to subscribe to my RSS feed.
Comments

Leave a response

  1. Avatar
    Matt King Fri, 27 Apr 2007 18:51:55 GMT

    This is great to know. I’ve used observers before, mostly in the context of caching views, but not for observing events in models. It seems to me that if you have more than one before_[whatever] or after_[whatever] in your model it’s probably best to move them into an observer. I have a few models that have a ton of these callbacks that will be nice to move out into another location. Thanks!

  2. Avatar
    Eric A. Fri, 27 Apr 2007 18:52:13 GMT

    Why not just use ActiveRecord callback hooks instead of Observers? Are Observers more powerful or is it just a matter of preference?

  3. Avatar
    Adam R. Fri, 27 Apr 2007 23:02:24 GMT

    Yeah, I’d like to know the benefits too. Can you shed some light on this Robby?

    (I’d also like the ability to use the logger from within an observer, but that’s another issue)

  4. Avatar
    Alain Ravet Sun, 29 Apr 2007 07:40:40 GMT

    Eric A

    > Why not just use ActiveRecord callback hooks instead of Observers?
    2 rules of thumb:
    • if a model could become invalid should the triggered action not take place, use AR hooks.
    • if the triggered action modifies the model (ex: pre-render and cache textile text in the model), use AR hooks.

    Otherwise use/consider observers.

  5. Avatar
    sjs Sun, 29 Apr 2007 18:59:26 GMT

    Creating a new record may be cause for some action to be triggered. If that action is tangential to the model which triggers it then it makes sense to keep that action separate. The AR docs have some logical examples that should help you see the point of using observers.

    Observers use the same AR callbacks. You don’t use observers as a replacement for AR callbacks; observers augment the usefulness of the AR callbacks.

  6. Avatar
    Robby Russell Mon, 30 Apr 2007 00:19:36 GMT Recommend me on Working with Rails

    Thanks for the comments!

    I’ve posted a follow up to this article with responses to some of our questions.

  7. Avatar
    Michael Hendrickx Fri, 07 Aug 2009 14:56:43 GMT

    Do observers “block” the rendering?

    If you have a timely job to be done upon a model.save, would it pause the rendering until it is done?

    I am implementing a module that will email a comment, but this will go to a few 100 people. I don’t want the submitter to wait for minutes while this is happening.

    Thank you, Michael

  8. Avatar
    Robby Russell Sat, 08 Aug 2009 20:41:22 GMT Recommend me on Working with Rails

    Michael,

    Yes, it’d be part of the request/response cycle. You could pass it off via Ajax or delegate to a background task (bj?)

  9. Avatar
    Gordon Yeong Tue, 19 Jan 2010 22:43:46 GMT

    hi, there :) and http://api.rubyonrails.org//

    Good post :)
    I refered to http://guides.rubyonrails.org/action_mailer_basics.html

    I am a bit unclear about observers.

    Consider the set up below:

    model/part_mailer.rb —-—-—-—-—-- class PartMailer < ActionMailer::Base @admin_email = ‘admin@sample.com’ @from_email = ‘admin-sales@sample.com

    def created_succesfully(part)
      recipients user.email, @admin_email
      from @from_email
      subject "MyApp - New part created." 
      body :user => user
    end

    model/part_observer.rb —-—-—-—-—-——

    class PartObserver < ActiveRecord::Observer def after_create(part) PartMailer.deliver_created_succesfully(part) end end

    It looks as if I can only pass in the object of the given class into the observer. In the case above, ‘part’ is the only one that is being passed by to deliver_created_successfully in model/part_observer.rb. part_mailer.rb)? I tried looking at the api docs and http://guides.rubyonrails.org/action_mailer_basics.html to no success. Can someone please shed some light into this?

    Can I pass more objects to the method, created_successfully (model/

    Thanks! :)

  10. Avatar
    Blackjack virtuale Fri, 19 Feb 2010 07:28:56 GMT

    I have a minor css issue and wonder if someone sees something obvious. This menu looks good in FireFox and IE7 but in IE8, unless I use compatibility mode, the menu li renders odd – double bullets or the link is below and right of the li. I’m not sure if this is IE8’s problem or the structure I have here.

  11. Avatar
    abercrombie clothes Thu, 18 Mar 2010 06:28:00 GMT

    I’m not sure if this is IE8’s problem or the structure I have here.

  12. Avatar
    wholesale shoes Thu, 13 May 2010 03:46:11 GMT

    Welcome to check on our website!Any needs or any orther questions, welcome to contact us at any time ! Shopping online offers lots of benefits that you won’t find shopping in a store or by mail. The Internet is always open — seven days a week, 24 hours a day — and bargainscan be numerous online.With a click of a mouse, you can buy an airline ticket, book a hotel, send flowers to a friend .

  13. Avatar
    wholesale laptop adapter Thu, 13 May 2010 06:30:34 GMT

    It appears that the Agile Web Development with Rails book is still encouraging people to do the following in order to load an Observer.

  14. Avatar
    all star shoes Thu, 13 May 2010 16:34:14 GMT
  15. Avatar
    all star shoes Thu, 13 May 2010 16:34:15 GMT
  16. Avatar
    LV Bags Sat, 29 May 2010 02:16:41 GMT

    LV Bags

  17. Avatar
    Zoom Lebron 7 Sat, 29 May 2010 02:17:07 GMT

    Zoom Lebron 7

  18. Avatar
    nike lebron Wed, 09 Jun 2010 08:21:08 GMT

    TR RT R

  19. Avatar
    dunk sb mid Wed, 09 Jun 2010 08:21:24 GMT

    RTY TR

  20. Avatar
    Christian Louboutin Boots Wed, 16 Jun 2010 03:21:22 GMT

    good

  21. Avatar
    ebuyshoesstore Sun, 20 Jun 2010 14:38:59 GMT

    Thanks for sharing,please come to ourdesignershoesstore

  22. Avatar
    ebuyshoesstore Sun, 20 Jun 2010 14:38:59 GMT

    Thanks for sharing,please come to ourdesignershoesstore

  23. Avatar
    Kevin Poetry Tue, 29 Jun 2010 06:41:11 GMT

    I’m a bit late to this party, but thought I’d say that I found this useful today. Thanks!

  24. Avatar
    air jordan 11 Wed, 30 Jun 2010 09:08:55 GMT

    Demonstrate a unique new conceptjordan shoesAwA.6

  25. Avatar
    ccccccccccc Wed, 14 Jul 2010 09:23:10 GMT
  26. Avatar
    http://www.guccisaleoutlet.com/ Sat, 17 Jul 2010 03:04:00 GMT

    no spam here

  27. Avatar
    Marriage Counseling      Sat, 17 Jul 2010 20:23:39 GMT

    Marriage Counseling

  28. Avatar
    start sharing not selling Sun, 18 Jul 2010 13:26:30 GMT

    wow its nice tips to me to learn about HTML so thanks

  29. Avatar
    Online Electronic Products Sat, 24 Jul 2010 06:34:27 GMT

    You have a point. Very insightful. A nice different perspective.

  30. Avatar
    Online Electronic ProductsHoliday Tour Guide Sat, 24 Jul 2010 06:34:47 GMT

    Thanks for this article. It’s just what I was searching for. I am always interested in this subject. Will bookmark it.

  31. Avatar
    dcsadasd Fri, 30 Jul 2010 06:12:12 GMT

    od dior belts Parents, Is Your Child a prada 2010 Bad Seed? One Mom Can’t Understand Roger Dubuis Watch Why

  32. Avatar
    Sobe Sun, 01 Aug 2010 14:04:37 GMT

    If you were hoping to meet up with me on one of these evenings, I apologize. I may be heading up to Seattle in the coming weeks anyways and if you sent me an email, I’ll let you know when I am planning to.

  33. Avatar
    wholesale nfl jerseys Thu, 05 Aug 2010 05:47:39 GMT

    Thanks for the list. I found them interesting and informative. I hope that you could add some more like the blogs of current issues such as an oil spill explosion.

  34. Avatar
    Louis Vuitton Sobe Clutch M93728 Thu, 05 Aug 2010 17:13:35 GMT

    so good

  35. Avatar
    Louis Vuitton Sobe Clutch M93729 Thu, 05 Aug 2010 17:15:20 GMT

    There are some discussions within the comments on the blog post about the design decisions that were made, some of which we’ve already begun to address in our redesign process brainstorming (based on google analytic conversion data).

  36. Avatar
    tool bag manufacturer Fri, 06 Aug 2010 03:22:41 GMT
  37. Avatar
    christian louboutin Sat, 07 Aug 2010 01:16:32 GMT

    Thanks for this information .I really appreciate your work, keep it up christian louboutin

  38. Avatar
    vibram fivefingers Sat, 07 Aug 2010 02:35:18 GMT

    Is very good to read more books .

  39. Avatar
    nike shox Sat, 07 Aug 2010 03:45:41 GMT

    colleague is wonderful period in life.

  40. Avatar
    Travel Jakarta Bandung Sun, 08 Aug 2010 19:58:02 GMT

    I found so many interesting stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! Keep up the excellent work.

  41. Avatar
    Gucci Wed, 11 Aug 2010 02:48:34 GMT

    replica designer walletsLV Louis Vuitton Shoulder bags from Louis VuittonGucci bags walletsLouis Vuitton handbags

Share your thoughts... (really...I want to hear them)

Comments