Class: Wsv::Response::SseBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/wsv/response/sse_builder.rb

Overview

Builds a Server-Sent Events Response.

Wsv::Response.sse do |io|
  io.write("data: ping\n\n")
  io.flush
end

‘Connection: close` is set by Response#write_to, so the body terminates when the producer block returns. SSE clients (browsers) re-connect automatically.

Constant Summary collapse

DEFAULT_HEADERS =
{
  "Content-Type" => "text/event-stream; charset=utf-8",
  "Cache-Control" => "no-cache",
  # X-Accel-Buffering disables response buffering on reverse proxies
  # that respect it (nginx). Without this an SSE stream behind a
  # proxy would only deliver after the connection ended.
  "X-Accel-Buffering" => "no"
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(status: 200, headers: {}, &producer) ⇒ SseBuilder

Returns a new instance of SseBuilder.



27
28
29
30
31
# File 'lib/wsv/response/sse_builder.rb', line 27

def initialize(status: 200, headers: {}, &producer)
  @status = status
  @headers = DEFAULT_HEADERS.merge(headers)
  @producer = producer
end

Instance Method Details

#buildObject



33
34
35
36
37
38
39
# File 'lib/wsv/response/sse_builder.rb', line 33

def build
  Response.new(
    status: @status,
    headers: @headers,
    body: SseBody.new(&@producer)
  )
end