Skip to content

Commit

Permalink
Merge pull request #136 from cucumber/event-bus-queue-alternative
Browse files Browse the repository at this point in the history
Replay previous events to new subscribers
  • Loading branch information
danascheider authored Jun 24, 2017
2 parents 80f2926 + e7023db commit fd7bd7f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/cucumber/core/event_bus.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class EventBus
def initialize(registry = Events.registry)
@event_types = registry.freeze
@handlers = {}
@event_queue = []
end

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

# Broadcast an event
def broadcast(event)
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)
handlers_for(event.class).each { |handler| handler.call(event) }
@event_queue << event
end

def method_missing(event_id, *args)
Expand All @@ -39,6 +42,14 @@ def method_missing(event_id, *args)

private

def broadcast_queued_events_to(handler, event_type)
@event_queue.select { |event|
event.class == event_type
}.each { |event|
handler.call(event)
}
end

def handlers_for(event_class)
@handlers[event_class.to_s] ||= []
end
Expand Down
12 changes: 12 additions & 0 deletions spec/cucumber/core/event_bus_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,18 @@ def on_test_event(event)
expect(handler.received_payload.some_attribute).to eq :some_attribute
end

it "sends events that were broadcast before you subscribed" do
event_bus.test_event :some_attribute
event_bus.another_test_event

received_payload = nil
event_bus.on(:test_event) do |event|
received_payload = event
end

expect(received_payload.some_attribute).to eq(:some_attribute)
end

end

it "will let you inspect the registry" do
Expand Down

0 comments on commit fd7bd7f

Please sign in to comment.