Skip to content

Instantly share code, notes, and snippets.

@universal
Last active November 3, 2016 13:02
Show Gist options
  • Save universal/97052d55273bf86e3cd612c1191aa6b0 to your computer and use it in GitHub Desktop.
Save universal/97052d55273bf86e3cd612c1191aa6b0 to your computer and use it in GitHub Desktop.
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