Created
September 8, 2012 14:37
-
-
Save benolee/3675497 to your computer and use it in GitHub Desktop.
Events
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
| 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