HonestPubsub

Simple Publishers and subscribers for Ruby using RabbitMQ

Installation

Add this line to your application's Gemfile:

gem 'honest_pubsub'

And then execute:

$ bundle

Or install it yourself as:

$ gem install honest_pubsub

You also need to install RabbitMQ

$ brew install rabbitmq

Usage

There are two sides to this gem, publishers and subscribers

Publishers

Publishing to a message is super simple

HonestPubsub.publish('user.created', { id: 3, name: 'Foo Bar', email: '[email protected]')

Additionally you can setup a context that is passed down to the subscribers. This context can be set up in a before_filter

class ApplicationController < ActionController::Base
    before_filter :setup_pubsub_context

    private

    def setup_pubsub_context
        HonestPubsub::Context.setup_context
          unique_id:       request.uuid,
          orig_ip_address: request.remote_ip,
          application:     "my_app/web:#{self.class.name.underscore}/#{action_name}",
          user_id:         current_user.try(:id)
    end
end

Context is automatically cleared up by the gem for a Rails Application. Otherwise, you can call HonestPubsub::Context.clear!

Subscribers

You can declare a subscriber class as follows

class UserWelcomeSubscriber < HonestPubsub::Subscriber
  subscribe_to "user_created" # The message prefix that you're subscribing to
  # subscribe_to "user_created", on: 'welcome_emails_queue' # If you want to specify the queue name

  def perform(payload)
    # My awesome logic goes here...
  end
end

You also run subscribers in a separate process to consume the message using the provided executable

bundle exec start_subscribers

You can execute bundle exec start_subscribers --help to see all the various options that it providers

Usage: bundle exec start_subscribers [options]
    -P, --pidfile PATH               path to pidfile
    -o, --only [SUBSCRIBERS]         comma separated name of subsriber classes that should be run
    -r, --require [PATH|DIR]         Location of Rails application with workers or file to require
    -v, --version                    Print version and exit

Validations

class UserWelcomeSubscriber < HonestPubsub::Subscriber
  subscribe_to "user_created" # The message prefix that you're subscribing to
  validates_payload_with :id_present
  validates_payload_with do |payload|
    payload[:email].present?
  end

  def perform(payload)
    # My awesome logic goes here...
  end

  private

  def id_present(payload)
    payload[:id].present?
  end
end

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request