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.
Intallation
gem sources -a http://gems.github.com
sudo gem install zilkey-switchboard
Usage
First, require switchboard above your rails initializer:
environment.rb
require ‘switchboard’
Rails::Initializer.run do |config|
# …
end
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
end
def after_update(record)
description = "#{record.class.name} was updated"
publish_activity_feed_items record, description
end
def after_destroy(record)
description = "#{record.class.name} was deleted"
publish_activity_feed_items record, description
end
def publish_activity_feed_items(record, description)
record.activity_feed_item_subscribers.each do |subscriber|
ActivityFeedItem.create :user => subscriber, :description =>
description
end
end
private :publish_activity_feed_items
end
end
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
Switchboard.listeners.clear
end
end
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
end
end
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”
end
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”
end
To contribute: