Skip to content

Commit fd7bd7f

Browse files
authored
Merge pull request #136 from cucumber/event-bus-queue-alternative
Replay previous events to new subscribers
2 parents 80f2926 + e7023db commit fd7bd7f

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lib/cucumber/core/event_bus.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class EventBus
1515
def initialize(registry = Events.registry)
1616
@event_types = registry.freeze
1717
@handlers = {}
18+
@event_queue = []
1819
end
1920

2021
# Register for an event. The handler proc will be called back with each of the attributes
@@ -24,12 +25,14 @@ def on(event_id, handler_object = nil, &handler_proc)
2425
validate_handler_and_event_id!(handler, event_id)
2526
event_class = event_types[event_id]
2627
handlers_for(event_class) << handler
28+
broadcast_queued_events_to handler, event_class
2729
end
2830

2931
# Broadcast an event
3032
def broadcast(event)
3133
raise ArgumentError, "Event type #{event.class} is not registered. Try one of these:\n#{event_types.values.join("\n")}" unless is_registered_type?(event.class)
3234
handlers_for(event.class).each { |handler| handler.call(event) }
35+
@event_queue << event
3336
end
3437

3538
def method_missing(event_id, *args)
@@ -39,6 +42,14 @@ def method_missing(event_id, *args)
3942

4043
private
4144

45+
def broadcast_queued_events_to(handler, event_type)
46+
@event_queue.select { |event|
47+
event.class == event_type
48+
}.each { |event|
49+
handler.call(event)
50+
}
51+
end
52+
4253
def handlers_for(event_class)
4354
@handlers[event_class.to_s] ||= []
4455
end

spec/cucumber/core/event_bus_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,18 @@ def on_test_event(event)
136136
expect(handler.received_payload.some_attribute).to eq :some_attribute
137137
end
138138

139+
it "sends events that were broadcast before you subscribed" do
140+
event_bus.test_event :some_attribute
141+
event_bus.another_test_event
142+
143+
received_payload = nil
144+
event_bus.on(:test_event) do |event|
145+
received_payload = event
146+
end
147+
148+
expect(received_payload.some_attribute).to eq(:some_attribute)
149+
end
150+
139151
end
140152

141153
it "will let you inspect the registry" do

0 commit comments

Comments
 (0)