Last active
June 4, 2018 08:38
-
-
Save wikiti/79a212e07e95635998fbe83382e0b151 to your computer and use it in GitHub Desktop.
Ruby pub-sub implementation example
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 Pubsub | |
class EventBus | |
attr_reader :topics | |
def initialize | |
@topics = {} | |
end | |
def publish(topic, message) | |
topics[topic.to_s].to_a.each do |subscriber| | |
subscriber.send(topic, message) | |
end | |
end | |
def subscribe(topic, obj) | |
topics[topic.to_s] ||= [] | |
return if topics[topic.to_s].include?(obj) | |
topics[topic.to_s] << obj | |
end | |
def unsubscribe(topic, obj) | |
topics[topic.to_s] ||= [] | |
topics[topic.to_s].delete(obj) | |
end | |
end | |
module Publisher | |
def publish(topic, message = nil) | |
Pubsub.event_bus.publish(topic, message = nil) | |
end | |
end | |
module Subscriber | |
def subscribe(topic) | |
Pubsub.event_bus.subscribe(topic, self) | |
end | |
def unsubscribe(topic) | |
Pubsub.event_bus.unsubscribe(topic, self) | |
end | |
end | |
def self.event_bus | |
@event_bus ||= EventBus.new | |
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 'pubsub' | |
class P | |
include Pubsub::Publisher | |
end | |
class S | |
include Pubsub::Subscriber | |
def echo(_message) | |
puts "echo" | |
end | |
def test(_message) | |
puts "test" | |
end | |
end | |
p = P.new | |
s = S.new | |
puts '- S is not subscribed' | |
p.publish('test') | |
p.publish('echo') | |
puts '- S subscribed to echo' | |
s.subscribe('echo') | |
p.publish('test') | |
p.publish('echo') | |
puts '- S subscribed to test' | |
s.subscribe('test') | |
p.publish('test') | |
p.publish('echo') | |
puts '- S resubscribed to echo' | |
s.subscribe('echo') | |
p.publish('test') | |
p.publish('echo') | |
puts '- S unsubscribed from echo' | |
s.unsubscribe('echo') | |
p.publish('test') | |
p.publish('echo') | |
puts '- S unsubscribed from test' | |
s.unsubscribe('test') | |
p.publish('test') | |
p.publish('echo') | |
# Outputs the following: | |
# - S is not subscribed | |
# - S subscribed to echo | |
# echo | |
# - S subscribed to test | |
# test | |
# echo | |
# - S resubscribed to echo | |
# test | |
# echo | |
# - S unsubscribed from echo | |
# test | |
# - S unsubscribed from test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment