Skip to content

Instantly share code, notes, and snippets.

@lloeki
Created May 29, 2012 07:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lloeki/2823045 to your computer and use it in GitHub Desktop.
Save lloeki/2823045 to your computer and use it in GitHub Desktop.
Streaming (CSV) data in Rails 3.2
class FooController
respond_to :csv
def index
@foos = Foo.scoped
if stale?(:last_modified => Foo.something)
respond_with @gta do |format|
format.csv { stream_csv @foo }
end
end
end
def stream_csv(resource, options)
stream_resource do |y|
# csv headers
y << resource.klass.to_csv_header
# csv rows
resource.find_each(options) { |item|
y << item.to_csv
}
end
end
def stream_resource(&block)
# theoretically this should make unicorn pass-through
headers['X-Accel-Buffering'] = 'no'
# OK, and generate stream
self.status = 200
self.response_body = Enumerator.new &block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment