Class: HTTTee::Server::SSE::Body

Inherits:
Object
  • Object
show all
Includes:
EventMachine::Deferrable
Defined in:
lib/htttee/server/sse/body.rb

Constant Summary collapse

MESSAGE =
'message'
CTRL =
'ctrl'
EOF =
'eof'
CTRL_TABLE =
{
  "\n"    => 'newline',
  "\r"    => 'carriage-return',
  "\r \n" => 'crlf',
}

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ Body

Returns a new instance of Body.



17
18
19
# File 'lib/htttee/server/sse/body.rb', line 17

def initialize(body)
  @body = body
end

Instance Method Details

#call(chunks) ⇒ Object



21
22
23
24
25
# File 'lib/htttee/server/sse/body.rb', line 21

def call(chunks)
  chunks.each do |chunk|
    send_chunk(chunk)
  end
end

#each(&blk) ⇒ Object



65
66
67
# File 'lib/htttee/server/sse/body.rb', line 65

def each(&blk)
  @body.each(&blk)
end

#send(type, data, term) ⇒ Object



55
56
57
# File 'lib/htttee/server/sse/body.rb', line 55

def send(type, data, term)
  @body.call(["#{type}: #{data}#{term}"])
end

#send_chunk(chunk) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/htttee/server/sse/body.rb', line 27

def send_chunk(chunk)
  data, ctrl, remaining = chunk.partition(%r{\r \n|\n|\r})

  send_data(data)             unless data.empty?
  send_ctrl(CTRL_TABLE[ctrl]) unless ctrl.empty?
  send_chunk(remaining)       unless remaining.empty?
end

#send_ctrl(type) ⇒ Object



41
42
43
44
45
# File 'lib/htttee/server/sse/body.rb', line 41

def send_ctrl(type)
  send_event(CTRL)

  send_message(type)
end

#send_data(data) ⇒ Object



35
36
37
38
39
# File 'lib/htttee/server/sse/body.rb', line 35

def send_data(data)
  send_event(MESSAGE)

  send_message(data)
end

#send_event(event) ⇒ Object



51
52
53
# File 'lib/htttee/server/sse/body.rb', line 51

def send_event(event)
  send "event", event, "\n"
end

#send_message(data) ⇒ Object



47
48
49
# File 'lib/htttee/server/sse/body.rb', line 47

def send_message(data)
  send "data", data, "\n\n"
end

#succeedObject



59
60
61
62
63
# File 'lib/htttee/server/sse/body.rb', line 59

def succeed
  send_ctrl(EOF)

  @body.succeed
end