Created
September 13, 2017 20:49
-
-
Save joeybeninghove/a621e9e00bfa543ab406a40be4942b38 to your computer and use it in GitHub Desktop.
Tiny Pub/Sub in Ruby
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 Notifier | |
attr_reader :events | |
def initialize | |
@events = {} | |
end | |
def subscribe(event, &handler) | |
@events[event] ||= [] | |
@events[event] << handler | |
end | |
def broadcast(event, data=nil) | |
return if @events[event].nil? | |
@events[event].each do |handler| | |
handler.call(data) | |
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
describe Notifier do | |
describe "#subscribe" do | |
it "adds the given handler to the specified event" do | |
notifier = Notifier.new | |
block = lambda {} | |
notifier.subscribe("foo", &block) | |
expect(notifier.events["foo"]).to include block | |
end | |
context "when called twice for the same event" do | |
it "adds the second handler to the same event" do | |
notifier = Notifier.new | |
block1 = lambda {} | |
block2 = lambda {} | |
notifier.subscribe("foo", &block1) | |
notifier.subscribe("foo", &block2) | |
expect(notifier.events["foo"]).to include block1 | |
expect(notifier.events["foo"]).to include block2 | |
end | |
end | |
end | |
describe "#broadcast" do | |
it "calls the handlers for the given event" do | |
notifier = Notifier.new | |
block = lambda { |data| puts data } | |
notifier.subscribe("foo", &block) | |
expect(block).to receive(:call).with("bar") | |
notifier.broadcast("foo", "bar") | |
end | |
it "does NOT call handlers for other events" do | |
notifier = Notifier.new | |
block1 = lambda { |data| puts data } | |
block2 = lambda { |data| puts data } | |
notifier.subscribe("foo1", &block1) | |
notifier.subscribe("foo2", &block1) | |
expect(block1).to receive(:call).with("bar") | |
expect(block2).not_to receive(:call).with("bar") | |
notifier.broadcast("foo1", "bar") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment