Created
May 29, 2012 07:05
-
-
Save lloeki/2823045 to your computer and use it in GitHub Desktop.
Streaming (CSV) data in Rails 3.2
This file contains hidden or 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 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