Kill ActiveRecord observers

Killing observers

  • decreases startup time by not loading all your models
  • makes it possible to preload config/environment.rb and still test models -> spin/zeus
  • makes dependencies obvious
  • replaces ActiveRecord magic with ruby
  • makes your app Rails 4 ready


# config/environment.rb
config.observers = [:foo_observer] 

# app/observers/foo_observer.rb
class FooObserver < ActiveRecord::Observer
  observes :user

  def after_save(user)


# app/models/user.rb
class User < ActiveRecord::Base
  include FooObserver

# app/observers/foo_observer.rb
module FooObserver
  class << self
    def included(base)
      this = self
      base.after_save{|user| this.more_descriptive_name(user) }

    def more_descriptive_name(user)

3 thoughts on “Kill ActiveRecord observers

  1. Or, even simpler / easier to test, you can use a callback class (check ActiveRecord::Callbacks docks, but basically you call before_save with an object that respons to before_save etc)

    • Nice idea, definitely simpler when there is only 1 action like before_save etc, and 1 less include is always nice, not sure if it’s still the best solution when there are multiple callbacks like before_save and before_create

    • Just tried in in a bigger project and it works nicely for 1 observer vs 1 item, but as soon as I got to multiple items I felt like repeating the before|after_save|update|destroy knowledge -> felt un-dry

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s