Skip to content

Instantly share code, notes, and snippets.

@TrumpClone
Created March 21, 2017 15:46
Show Gist options
  • Save TrumpClone/73f5b9f7240a77a41146f3b645a348c3 to your computer and use it in GitHub Desktop.
Save TrumpClone/73f5b9f7240a77a41146f3b645a348c3 to your computer and use it in GitHub Desktop.
Event Dispatcher
class Events::EventDomain::Base
class << self
def self_descriptor
name.demodulize.underscore.to_sym
end
end
def self_descriptor
self.class.self_descriptor
end
end
module Events::EventDomain
class NewNotification < Base
end
end
module Events::EventDomain
class NewRegisteredUser < Base
end
end
module Events::EventDomain
class NewTicket < Base
end
end
module Events::Infrastructure::Dispatcher
module_function
def dispatch(event_name, **payload)
Events::Infrastructure::ManagerRegistry.load_manager(event_name, payload).emit_event!
end
end
class Events::Infrastructure::Emitter < ActiveJob::Base
module_function
def emit!(event_name, **payload)
perform_later(event_name, payload)
end
def perform(event_name, **payload)
Events::Infrastructure::Dispatcher.dispatch(event_name, payload)
end
end
module Events::Infrastructure::EventRegistry
module_function
def load_event(event_name)
resolve(event_name)
end
def resolve(event_name)
"Events::EventDomain::#{event_name.to_s.camelize}".constantize
end
end
module Events::Infrastructure::ManagerRegistry
module_function
def load_manager(event_name, **payload)
resolve(event_name).new(payload)
end
def resolve(event_name)
"Events::Managers::#{event_name.to_s.camelize}".constantize
end
end
class Events::Managers::Base
include Events::Managers::Observable
attr_reader :payload
def initialize(**payload)
@payload = payload
end
def emit_event!
subscribers.each do |subscriber|
subscriber.process_event(event, payload) # PROCESS_EVENT SHOULD BE ABSRTRACTED BY Subscribable!!!
end
end
end
module Events::Managers::Observable
class << self
def included(base_class)
base_class.extend ClassMethods
end
end
def subscribers
self.class.subscribers
end
def event
self.class.event
end
module ClassMethods
def event
event_name = self.class.name.demodulize.underscore
Events::Infrastructure::EventRegistry.load_event(event_name)
end
def subscribers
@subscribers ||= []
end
def observe(subscriber)
subscribers.push(subscriber)
end
def unobserve(subscriber)
subscribers.delete(subscriber)
end
end
end
class Events::Managers::NewNotification < Events::Managers::Base
observe Distribution::Transmition::Workers::EventRunner
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment