Skip to content

Instantly share code, notes, and snippets.

@benolee
Created September 8, 2012 14:37
Show Gist options
  • Select an option

  • Save benolee/3675497 to your computer and use it in GitHub Desktop.

Select an option

Save benolee/3675497 to your computer and use it in GitHub Desktop.
Events
require 'bundler/setup'
Bundler.require :default
require 'securerandom'
require 'active_support/notifications'
require 'active_support/concern'
module Events
include ActiveSupport::Concern
def on(event_type, &handler)
ActiveSupport::Notifications.subscribe(event_type) do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
handler.call(event)
end
end
def fire(event_type)
ActiveSupport::Notifications.instrument(event_type, target: self)
end
module ClassMethods
def on(object, event_type, &handler)
ActiveSupport::Notifications.subscribe(event_type, &handler)
end
def fire(object, event_type)
ActiveSupport::Notifications.instrument(event_type, target: object)
end
end
end
bob = Object.new
bob.extend Events
bob.on 'message' do |event|
data = {name: event.name, duration: event.duration, payload: event.payload}
puts "bob got: #{data.inspect}"
end
bob.fire 'message'
bob.fire 'nohandler'
bob.fire 'message'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment