Skip to content

Instantly share code, notes, and snippets.

@smsohan
Created March 20, 2013 21:26
Show Gist options
  • Save smsohan/5208617 to your computer and use it in GitHub Desktop.
Save smsohan/5208617 to your computer and use it in GitHub Desktop.
Stream CSV data in Rails 3.2
class ExportController < ApplicationController
def index
#suitable for streaming data, no caching http://wiki.nginx.org/X-accel#X-Accel-Buffering
headers['X-Accel-Buffering'] = 'no'
headers["Cache-Control"] ||= "no-cache"
headers.delete("Content-Length")
headers["Content-Type"] = "text/csv"
headers["Content-disposition"] = 'attachment; filename="gaga.csv"'
response.status = 200
self.response_body = csv_lines
end
def csv_lines
Enumerator.new do |y|
y << "name, number\n"
5.times do |i|
y << "gaga, #{i}\n"
sleep 2
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment