Method: Etna::Controller#try_stream

Defined in:
lib/etna/controller.rb

#try_stream(content_type, &block) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/etna/controller.rb', line 52

def try_stream(content_type, &block)
  if @request.env['rack.hijack?']
    @request.env['rack.hijack'].call
    stream = @request.env['rack.hijack_io']

    headers = [
      "HTTP/1.1 200 OK",
      "Content-Type: #{content_type}"
    ]
    stream.write(headers.map { |header| header + "\r\n" }.join)
    stream.write("\r\n")
    stream.flush

    Thread.new do
      block.call(stream)
    ensure
      stream.close
    end

    # IO is now streaming and will be processed by above thread.
    @response.close
  else
    @response['Content-Type'] = content_type
    block.call(@response)
    @response.finish
  end
end