Switchboard - Easy to use global ActiveRecord event listeners

Switchboard is a simple, event-observing framework for ActiveRecord.
It's designed to make it easy to add observers for all models in your
app, and to easily turn them on and off selectively.


  gem sources -a http://gems.github.com
  sudo gem install zilkey-switchboard


First, require switchboard above your rails initializer:

  # environment.rb
  require 'switchboard'
  Rails::Initializer.run do |config|
    # ...

Add the listeners to the Switchboard in an initializer:

  # config/initializers/switchboard.rb
  Switchboard.listeners << ActivityFeedListener

Then, create a listener class that defines methods for after_create,
after_update and after_destroy:

class ActivityFeedListener
  class << self
    def after_create(record)
      description = "#{record.class.name} was created"
      publish_activity_feed_items record, description

    def after_update(record)
      description = "#{record.class.name} was updated"
      publish_activity_feed_items record, description

    def after_destroy(record)
      description = "#{record.class.name} was deleted"
      publish_activity_feed_items record, description

    def publish_activity_feed_items(record, description)
      record.activity_feed_item_subscribers.each do |subscriber|
        ActivityFeedItem.create :user => subscriber, :description =>

    private :publish_activity_feed_items

Notice how these classes are almost identical to
ActiveRecord::Observer subclasses, designed so that it's easy to
refactor from one to the other.

When unit testing if your listeners are all firing your unit tests
become integration tests. To avoid this, you can easily turn off
listeners for all specs all the time:

Spec::Runner.configure do |config|
  config.before(:each) do

Then, when you want them back on again, you can either turn them back
on for a spec:

describe "Integrating with listeners" do
  before do
    Switchboard.listeners << FooListener

When doing data imports, migrations or certain actions that need to
only use certain listeners, you can easily specify which ones you'd
like to use:

Switchboard.with_listeners AuditListener, ActivityListener do
  Article.create! :title => "foo"

After the block runs, the original listeners are restored.

If you want to run some code with no listeners, you can do so with:

Switchboard.without_listeners do
  Article.create! :title => "foo"

To contribute:


Github is flaking out ATM, so I can't check the source, but is there a
reason that you're wanting people to load your gem like this? It
breaks the ability of 'rake gems' and friends to unpack/install/verify
the gem.

--Matt Jones