Class: Mediator::Instance
- Inherits:
-
Object
- Object
- Mediator::Instance
- Defined in:
- lib/mediator.rb
Constant Summary collapse
- MultipleHandlers =
Class.new(StandardError)
- UnregisteredHandler =
Class.new(StandardError)
Instance Method Summary collapse
- #accept(request) ⇒ Object
- #handle(klass, handler) ⇒ Object
-
#initialize ⇒ Instance
constructor
A new instance of Instance.
- #publish(event) ⇒ Object
- #subscribe(klass, handler) ⇒ Object
Constructor Details
#initialize ⇒ Instance
Returns a new instance of Instance.
12 13 14 15 |
# File 'lib/mediator.rb', line 12 def initialize @handlers = Concurrent::Map.new @listeners = Concurrent::Map.new { |h, k| h.compute_if_absent(k) { [] } } end |
Instance Method Details
#accept(request) ⇒ Object
27 28 29 30 31 |
# File 'lib/mediator.rb', line 27 def accept(request) handler!(request).then do |handler| handler.call(request) end end |
#handle(klass, handler) ⇒ Object
17 18 19 20 21 |
# File 'lib/mediator.rb', line 17 def handle(klass, handler) raise MultipleHandlers, "Multiple handlers not allowed for #{klass}" if handlers[klass] handlers[klass] = handler end |
#publish(event) ⇒ Object
33 34 35 36 37 |
# File 'lib/mediator.rb', line 33 def publish(event) listeners!(event).each do |listener| listener.call(event) end end |
#subscribe(klass, handler) ⇒ Object
23 24 25 |
# File 'lib/mediator.rb', line 23 def subscribe(klass, handler) listeners[klass] << handler end |