Created
March 20, 2014 16:31
-
-
Save zacheryph/9667997 to your computer and use it in GitHub Desktop.
pub/sub with ActiveSupport::Notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Eventable | |
extend self | |
def emit(event_name, instance = nil, payload = {}) | |
ActiveSupport::Notifications.publish(event_name, instance, payload) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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