Skip to content

Instantly share code, notes, and snippets.

@nhocki
Created June 1, 2012 03:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save nhocki/2848431 to your computer and use it in GitHub Desktop.
Save nhocki/2848431 to your computer and use it in GitHub Desktop.
Simple Async ActiveSupport::Notification example
# config/initializer/notification_center.rb
NotificationCenter.queue
NotificationCenter.thread
ActiveSupport::Notifications.subscribe /(.)+\.notification/i do |*args|
NotificationCenter.queue << args
end
# lib/notification_center.rb
require 'thread'
require 'active_support/notifications'
module NotificationCenter
def self.logger
Rails.logger
end
def self.queue
@queue ||= Queue.new
end
def self.thread
@thread ||= Thread.new do
while args = queue.pop
logger.fatal "\n\n\n\n"
event = ActiveSupport::Notifications::Event.new(*args)
logger.fatal "[#{event.name}] Starting Event"
logger.fatal "[#{event.name}] #{args}"
logger.fatal "[#{event.name}] #{event.duration}"
logger.fatal "[#{event.name}] #{event.payload}"
logger.fatal "\n\n\n\n"
end
end
end
def self.finish!
queue << nil
thread.join
@thread = nil
thread
end
end
# somewhere in the code
info = {
user: "nhocki",
email: "what",
message: "What's this?"
}
ActiveSupport::Notifications.notifier.instrument("fail.notification", :extra => info)
@tyrauber
Copy link

tyrauber commented Oct 8, 2014

Awesome stuff. Minor update for Rails 4.2.0.beta2.
https://gist.github.com/nhocki/2848431#file-somewhere-rb-L7
ActiveSupport::Notifications.instrument("fail.notification", info)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment