Created
April 21, 2011 09:09
-
-
Save mathieuravaux/934033 to your computer and use it in GitHub Desktop.
Streaming the contents of an em-http-request in a Rails response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def stream | |
@path = request[:path] | |
puts "1) grabbing the output" | |
already_called = false | |
self.response_body = work_around_double_call_bug { |resp, output| | |
return if already_called | |
already_called = true | |
puts "3) output grabbed: #{output}. Requesting Drobpox..." | |
dropbox_session.stream @path do |em_http_req| | |
req_fiber = Fiber.current | |
puts "4) Setting the EM callbacks..." | |
em_http_req.headers { |data| | |
puts "6) Got the headers" | |
headers['Content-Type'] = data['CONTENT_TYPE'] | |
headers['Content-Length'] = data['CONTENT_LENGTH'] | |
} | |
em_http_req.stream { |chunk| | |
print '>' | |
output.write chunk | |
} | |
em_http_req.callback { |res| | |
puts "8) Finished receiving data #{res}" | |
req_fiber.resume(:error) | |
} | |
em_http_req.errback { |err| req_fiber.resume(:error) } | |
puts "5) Pausing there !" | |
Fiber.yield | |
puts "9) All clear !" | |
end | |
} | |
puts "2) Finished the Request" | |
end | |
private | |
# To circumvent this Rails bug: | |
# https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4554-render-text-proc-regression#ticket-4554-15 | |
def work_around_double_call_bug &block | |
already_called = false | |
proc do |*args| | |
yield *args unless already_called | |
already_called = true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment