Class: Whoosh::Streaming::SSE

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ SSE

Returns a new instance of SSE.



18
19
20
21
# File 'lib/whoosh/streaming/sse.rb', line 18

def initialize(io)
  @io = io
  @closed = false
end

Class Method Details

.headersObject



9
10
11
12
13
14
15
16
# File 'lib/whoosh/streaming/sse.rb', line 9

def self.headers
  {
    "content-type" => "text/event-stream",
    "cache-control" => "no-cache",
    "connection" => "keep-alive",
    "x-accel-buffering" => "no"
  }.freeze
end

Instance Method Details

#<<(data) ⇒ Object



23
24
25
26
27
28
# File 'lib/whoosh/streaming/sse.rb', line 23

def <<(data)
  return if @closed
  formatted = data.is_a?(String) ? data : JSON.generate(data)
  write("data: #{formatted}\n\n")
  self
end

#closeObject



41
42
43
44
45
# File 'lib/whoosh/streaming/sse.rb', line 41

def close
  return if @closed
  event("close")
  @closed = true
end

#closed?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/whoosh/streaming/sse.rb', line 47

def closed?
  @closed
end

#event(name, data = nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/whoosh/streaming/sse.rb', line 30

def event(name, data = nil)
  return if @closed
  write("event: #{name}\n")
  if data
    formatted = data.is_a?(String) ? data : JSON.generate(data)
    write("data: #{formatted}\n")
  end
  write("\n")
  self
end