Class: Reel::Response::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/reel/response/writer.rb

Constant Summary collapse

CRLF =
"\r\n"

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Writer

Returns a new instance of Writer.



6
7
8
# File 'lib/reel/response/writer.rb', line 6

def initialize(socket)
  @socket = socket
end

Instance Method Details

#finish_responseObject

Finish the response and reset the response state to header



20
21
22
# File 'lib/reel/response/writer.rb', line 20

def finish_response
  @socket << "0#{CRLF * 2}"
end

#handle_response(response) ⇒ Object

Render a given response object to the network socket



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/reel/response/writer.rb', line 25

def handle_response(response)
  @socket << render_header(response)
  return response.render(@socket) if response.respond_to?(:render)

  case response.body
  when String
    @socket << response.body
  when IO
    Celluloid::IO.copy_stream(response.body, @socket)
  when Enumerable
    response.body.each { |chunk| write(chunk) }
    finish_response
  when NilClass
    # Used for streaming Transfer-Encoding chunked responses
    return
  else
    raise TypeError, "don't know how to render a #{response.body.class}"
  end
  response.body.close if response.body.respond_to?(:close)
end

#write(chunk) ⇒ Object

Write body chunks directly to the connection



11
12
13
14
15
16
17
# File 'lib/reel/response/writer.rb', line 11

def write(chunk)
  chunk_header = chunk.bytesize.to_s(16)
  @socket << chunk_header + CRLF
  @socket << chunk + CRLF
rescue IOError, Errno::EPIPE, Errno::ECONNRESET => ex
  raise Reel::SocketError, ex.to_s
end