Skip to content

Instantly share code, notes, and snippets.

@romansklenar
Created January 8, 2013 16:00
Show Gist options
  • Save romansklenar/4484934 to your computer and use it in GitHub Desktop.
Save romansklenar/4484934 to your computer and use it in GitHub Desktop.
Killing Rails observers

Killing Rails 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/models/user.rb
class User < ActiveRecord::Base
  ....
end
 
# 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)
      base.after_save{|user| more_descriptive_name(user) }
    end
 
    def more_descriptive_name(user)
      ...
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment