Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Last active September 16, 2015 15:42
Show Gist options
  • Save joshnesbitt/2706be8b5e3615b60b1c to your computer and use it in GitHub Desktop.
Save joshnesbitt/2706be8b5e3615b60b1c to your computer and use it in GitHub Desktop.
A very simple pub sub implementation.
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
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