Class: Spikard::SseEventProducer

Inherits:
Object
  • Object
show all
Defined in:
lib/spikard/sse.rb

Overview

Base class for SSE event producers.

Implement this class to generate Server-Sent Events.

Examples:

class NotificationProducer < Spikard::SseEventProducer
  def initialize
    @count = 0
  end

  def next_event
    sleep 1  # Wait 1 second between events

    return nil if @count >= 10  # End stream after 10 events

    event = Spikard::SseEvent.new(
      data: { message: "Notification #{@count}" },
      event_type: 'notification',
      id: @count.to_s
    )
    @count += 1
    event
  end

  def on_connect
    puts "Client connected to SSE stream"
  end

  def on_disconnect
    puts "Client disconnected from SSE stream"
  end
end

app = Spikard::App.new

app.sse('/notifications') do
  NotificationProducer.new
end

app.run

Instance Method Summary collapse

Instance Method Details

#next_eventSseEvent?

Generate the next event.

This method is called repeatedly to produce the event stream.

Returns:

  • (SseEvent, nil)

    SseEvent when an event is ready, or nil to end the stream.

Raises:

  • (NotImplementedError)


89
90
91
# File 'lib/spikard/sse.rb', line 89

def next_event
  raise NotImplementedError, "#{self.class.name} must implement #next_event"
end

#on_connectvoid

This method returns an undefined value.

Called when a client connects to the SSE endpoint.

Override this method to perform initialization when a client connects.



98
99
100
# File 'lib/spikard/sse.rb', line 98

def on_connect
  # Optional hook - default implementation does nothing
end

#on_disconnectvoid

This method returns an undefined value.

Called when a client disconnects from the SSE endpoint.

Override this method to perform cleanup when a client disconnects.



107
108
109
# File 'lib/spikard/sse.rb', line 107

def on_disconnect
  # Optional hook - default implementation does nothing
end