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

Before:

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

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

  def after_save(user)
    ....
  end
end

After:

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

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

    def more_descriptive_name(user)
      ...
    end
  end
end

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 to pragmatig Cancel reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s