Last active
September 16, 2015 15:42
-
-
Save joshnesbitt/2706be8b5e3615b60b1c to your computer and use it in GitHub Desktop.
A very simple pub sub implementation.
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
class Hub | |
class << self | |
NAMESPACE_SEPARATOR = ':' | |
def publish(event, payload = {}) | |
handlers[event].each do |handler| | |
handler.call(payload) | |
end | |
end | |
def subscribe(event, &block) | |
handlers[event] << block | |
end | |
def namespaces | |
names = handlers.keys | |
names.map! { |k| k.split(NAMESPACE_SEPARATOR).first } | |
names.uniq | |
end | |
private | |
def handlers | |
@handlers ||= Hash.new do |hash, key| | |
hash[key] = [] | |
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
require_relative('pub_sub.rb') | |
Hub.subscribe('user:register') do |payload| | |
puts "User with and ID of #{payload[:id]} registered." | |
end | |
Hub.subscribe('post:created') do |payload| | |
puts "Post with and ID of #{payload[:id]} created." | |
end | |
Hub.subscribe('test') do |payload| | |
puts "Hi there #{payload[:name]}!" | |
end | |
Hub.publish('user:register', id: 1) | |
Hub.publish('post:created', id: 2) | |
Hub.publish('test', name: 'Bob') | |
puts "Current namespaces:" | |
puts Hub.namespaces |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment