Last active
October 1, 2019 08:26
-
-
Save rubish/9598373 to your computer and use it in GitHub Desktop.
Pub/Sub using ActiveSupport::Notifications
This file contains hidden or 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 Publisher | |
extend self | |
def broadcast_event(event_name, payload={}) | |
if block_given? | |
ActiveSupport::Notifications.instrument(event_name, payload) do | |
yield | |
end | |
else | |
ActiveSupport::Notifications.instrument(event_name, payload) | |
end | |
end | |
end | |
# Usage | |
if user.save | |
Publisher.broadcast_event('user.created', user: user) | |
end | |
# Usage with block | |
def create_user(params) | |
user = User.new(params) | |
Publisher.broadcast_event('user.created', user: user) do | |
User.save! | |
# do some more important stuff here | |
end | |
end |
This file contains hidden or 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 Subscriber | |
def self.subscribe(event_name) | |
if block_given? | |
ActiveSupport::Notifications.subscribe(event_name) do |*args| | |
event = ActiveSupport::Notifications::Event.new(*args) | |
yield(event) | |
end | |
end | |
end | |
end | |
# Usage | |
Subscriber.subscribe('user.created') do |event| | |
error = "Error: #{event.payload[:exception].first}" if event.payload[:exception] | |
puts "#{event.transaction_id} | #{event.name} | #{event.time} | #{event.duration} | #{event.payload[:user].id} | #{error}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment