Class: Kreator::EventBus
- Inherits:
-
Object
- Object
- Kreator::EventBus
- Defined in:
- lib/kreator/event_bus.rb
Instance Method Summary collapse
-
#initialize ⇒ EventBus
constructor
A new instance of EventBus.
- #publish(type, payload = {}) ⇒ Object
- #subscribe(type = nil, &block) ⇒ Object (also: #on)
- #unsubscribe(*args) ⇒ Object
Constructor Details
#initialize ⇒ EventBus
Returns a new instance of EventBus.
5 6 7 8 |
# File 'lib/kreator/event_bus.rb', line 5 def initialize @subscribers = Hash.new { |hash, key| hash[key] = [] } @all_subscribers = [] end |
Instance Method Details
#publish(type, payload = {}) ⇒ Object
33 34 35 36 37 38 |
# File 'lib/kreator/event_bus.rb', line 33 def publish(type, payload = {}) event = payload.merge(type: type.to_s) @subscribers[type.to_s].each { |subscriber| subscriber.call(event) } @all_subscribers.each { |subscriber| subscriber.call(event) } event end |
#subscribe(type = nil, &block) ⇒ Object Also known as: on
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/kreator/event_bus.rb', line 10 def subscribe(type = nil, &block) raise ArgumentError, "block required" unless block if type @subscribers[type.to_s] << block else @all_subscribers << block end block end |
#unsubscribe(*args) ⇒ Object
23 24 25 26 27 28 29 30 31 |
# File 'lib/kreator/event_bus.rb', line 23 def unsubscribe(*args) type, subscriber = unsubscribe_args(args) if type @subscribers[type.to_s].delete(subscriber) else @all_subscribers.delete(subscriber) end end |