Skip to content

Instantly share code, notes, and snippets.

@RasPhilCo
Last active April 22, 2018 03:03
Show Gist options
  • Save RasPhilCo/89a032f4fc9d91f7e048b53e159d8b90 to your computer and use it in GitHub Desktop.
Save RasPhilCo/89a032f4fc9d91f7e048b53e159d8b90 to your computer and use it in GitHub Desktop.
require 'singleton'
class Subscriber
include Singleton
attr_reader :subscriptions
def initialize
@subscriptions = {}
end
def subscribe(event_name, callback)
subscriptions[event_name] = (subscriptions[event_name] || []).push(callback)
end
end
class Base
def self.run
new.run
end
def self.subscribe(event)
subscriber.subscribe(event, self)
end
def self.subscriber
Subscriber.instance
end
def emit(event, _data = nil)
Base.subscriber.subscriptions[event].each(&:run)
end
end
class B < Base
def run
puts "B subscribed to event"
end
end
class C < Base
def run
puts "C subscribed to event"
end
end
class A < Base
def run
while true
emit(:periodic_event)
sleep 5
end
end
end
B.subscribe(:periodic_event)
C.subscribe(:periodic_event)
A.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment