流式CSV下载从Rails 3.2应用程序 [英] Streaming CSV Download from Rails 3.2 app

查看:198
本文介绍了流式CSV下载从Rails 3.2应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝望得到一个流式CSV下载工作在我的Rails 3.2.2应用程序。

I am desperate to get a streaming CSV download working in my Rails 3.2.2 app.

我已经尝试过'csv_builder'gem(https://github.com/dasil003/csv_builder),它宣传支持这个功能,但是似乎有Rails 3.2中的一些变化使它无法工作(它在应用程序启动时产生一个未初始化的常量ActionView :: Template :: Handler错误)。

I have tried the 'csv_builder' gem (https://github.com/dasil003/csv_builder), which advertises support for this feature, however it seems that there were some changes in Rails 3.2 that are keeping it from working (it produces an 'uninitialized constant ActionView::Template::Handler' error on app startup).

或解决方案在那里?谢谢!

Any other ideas or solutions out there? Thanks!

编辑:为了说明,我需要将模型的所有条目导出为CSV文件。有这么多行,它是超时...因此需要流。我过去使用Comma gem(https://github.com/crafterm/comma),但它目前不支持流式传输。

To clarify, I am needing to export all entries of a model as a CSV file. There are so many rows, that it is timing out... therefore the need for streaming. I have used the Comma gem (https://github.com/crafterm/comma) for this in the past, but it doesn't support streaming either, at the moment.

推荐答案

好吧,经过一番更多的研究,我在我的控制器一起黑客入侵。它会流如果 response_body 给出一些枚举(是一个词?)。此外,服务器需要能够流(我在Heroku上使用Unicorn)。我想非常不喜欢在控制器中的所有这些东西,所以我的下一步是以某种方式提取它。

OK, after a bit more research I hacked together the following in my controller. It'll stream if response_body is given something enumeratable (is that a word?). Also, the server needs to be able to stream (I am using Unicorn on Heroku). I'd like very much to not have all this stuff in the controller, so my next step is to extract it out somehow.

  format.csv {
    @entries = Entry.all
    @columns = ["First Name", "Last Name"].to_csv
    @filename = "entries-#{Date.today.to_s(:db)}"

    self.response.headers["Content-Type"] ||= 'text/csv'
    self.response.headers["Content-Disposition"] = "attachment; filename=#{@filename}"
    self.response.headers["Content-Transfer-Encoding"] = "binary"

    self.response_body = Enumerator.new do |y|
      @entries.each_with_index do |entry, i|
        if i == 0
          y << @columns
        end
        y << [entry.first_name, entry.last_name].to_csv
      end
    end
  }

这篇关于流式CSV下载从Rails 3.2应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆