Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -41,6 +44,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