PubSub
PubSub is a thin wrapper around ActiveSupport::Notifications, which provides an implementation of the Publish/Subscribe pattern.
http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html
The goal was to be able to create more loosly coupled models by pulling side effects of our models into their own class. We wanted this behavior for Active Record classes as well as non-Active Record classes.
The result was a library that was:
- easy to test
- easy to disable (when using the console, during unit tests, etc.)
- easy to understand (b/c of AS::Notifications syncronous publishing queue)
Installation
Add this line to your application's Gemfile:
gem 'pub_sub'
And then execute:
$ bundle
Or install it yourself as:
$ gem install pub_sub
Usage
Configuration
PubSub.disable # disables publishing
PubSub.enable # enables publishing
By default, PubSub looks for subscribers in app/models/pub_sub/*
Within a plain ruby project
PubSub::Subscriber => provides an interface to subscribe to a topic
#
# Subscribe to the 'user_created' topic.
#
class SendWelcomeEmailToUser < PubSub::Subscriber
subscribe_to("user_created")
def on_publish
write_user_to_file(options[:user])
end
private
def write_user_to_file(user)
File.open("/tmp/users.txt", "w+") do |file|
file << user.name
end
end
end
#
# Publish a message to the 'user_created' topic
#
PubSub.publish("user_created", user:
User.new(name: 'John Doe')
)
Within a Rails project
PubSub::ActiveRecord::Subscriber => provide an interface to subscribe to an ActiveRecord callback topic
#
# Subscribe to the after_create callback of User
#
# currently, PubSub loads all subscribers in app/models/pub_sub/*
#
class SendWelcomeEmailToUser < PubSub::ActiveRecord::Subscriber
subscribe_to(User, 'after_create')
def on_publish
ApplicationMailer.send_welcome_email(record)
end
end
=> PubSub.subscribe("active_record::user::after_create")
#
# inside your application (controller, model, etc)
#
User.create(name: 'John Doe')
=> PubSub.publish("active_record::user::after_create")
Backlog / To Do
http://www.pivotaltracker.com/projects/705655
Feel free to take a look.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
Contributors
- Brent Wheeldon
- Cathy O'Connell
- Nick Monje
- Evan Goodberry
- Ben Moss
- Chien Kuo
- Edwin Chong
- Adam Berlin
- Rasheed Abdul-Aziz
- Ryan McGarvey
- Geoffrey Ducharme
- Alex Kramer