Last active
November 3, 2016 13:02
-
-
Save universal/97052d55273bf86e3cd612c1191aa6b0 to your computer and use it in GitHub Desktop.
This file contains 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
class StreamingCsvController < ApplicationController | |
def test | |
respond_to do |format| | |
format.csv {render_csv} | |
end | |
end | |
private | |
def render_csv | |
set_file_headers | |
set_streaming_headers | |
response.status = 200 | |
#setting the body to an enumerator, rails will iterate this enumerator | |
self.response_body = csv_lines | |
end | |
def set_file_headers | |
file_name = "transactions.csv" | |
headers["Content-Type"] = "text/csv" | |
headers["Content-disposition"] = "attachment; filename=\"#{file_name}\"" | |
end | |
def set_streaming_headers | |
#nginx doc: Setting this to "no" will allow unbuffered responses suitable for Comet and HTTP streaming applications | |
headers['X-Accel-Buffering'] = 'no' | |
headers["Cache-Control"] ||= "no-cache" | |
headers.delete("Content-Length") | |
end | |
def csv_lines | |
Enumerator.new do |y| | |
y << "#{["i", "rand"].join(",")}\n" | |
i = 1 | |
Datum.find_each do |d| | |
y << "#{d.i},#{d.value}\n" | |
puts "line #{d.i} added" | |
sleep 0.01 | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment