Skip to content

Instantly share code, notes, and snippets.

@zacheryph
Created March 20, 2014 16:31
Show Gist options
  • Save zacheryph/9667997 to your computer and use it in GitHub Desktop.
Save zacheryph/9667997 to your computer and use it in GitHub Desktop.
pub/sub with ActiveSupport::Notifications
module Eventable
module Emitter
extend ActiveSupport::Concern
included do
def emit(event_name, payload = {})
full_event = "#{self.class.to_s.underscore}:#{event_name}"
Eventable.emit full_event, self, payload
end
end
end
end
module Eventable
extend self
def emit(event_name, instance = nil, payload = {})
ActiveSupport::Notifications.publish(event_name, instance, payload)
end
end
module Eventable
module Subscriber
extend ActiveSupport::Concern
included do
@queue = :eventable
attr_accessor :event, :instance, :payload
def self.perform(event, instance, payload, callback)
self.new(event, instance, payload.with_indifferent_access).send(callback)
end
def self.on(klass, event_name, callback, options = {})
full_event = /^#{klass.to_s.underscore}:#{event_name}$/
ActiveSupport::Notifications.subscribe(full_event) do |event, instance, payload|
payload[:_class] = instance.class.name
payload[:_id] = instance.id if instance.is_a?(ActiveRecord::Base)
if options[:async]
Resque.enqueue(self, event, nil, payload, callback)
else
self.new(event, instance, payload).send(callback)
end
end
end
def initialize(event, instance, payload)
self.event = event
self.instance = instance
self.payload = payload
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment