Skip to content

Instantly share code, notes, and snippets.

@0xradical
Forked from lloeki/foo_controller.rb
Created November 12, 2012 23:10
Show Gist options
  • Save 0xradical/4062687 to your computer and use it in GitHub Desktop.
Save 0xradical/4062687 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