Ruby 1.9.2导出CSV字符串而不生成文件 [英] Ruby 1.9.2 export a CSV string without generating a file

查看:119
本文介绍了Ruby 1.9.2导出CSV字符串而不生成文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是无法得到'写作'下的'一个字符串'的例子文档中的示例

I just can't get the 'To a String' example under 'Writing' example in the documentation to work at all.

ruby​​ -v返回:
ruby​​ 1.9.2p290 -09 revision 32553)[x86_64-darwin10.8.0]

ruby -v returns: ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin10.8.0]

我无法使用的文档示例如下:

The example from the documentation I can't working is here:

csv_string = CSV.generate do |csv|
    csv << ["row", "of", "CSV", "data"]
    csv << ["another", "row"]
end

我得到的错误是: / p>

The error I get is:

wrong number of arguments (0 for 1)

所以看起来我缺少一个参数,在文档这里它说明:

So it seems like I am missing an argument, in the documentation here it states:

This method wraps a String you provide, or an empty default String

但是当我传入一个空字符串,它给我以下错误:

But when I pass in a empty string, it gives me the following error:

No such file or directory - 

我不想生成一个csv文件,我只是想创建一个csv字符串,我作为文本发送给用户。

I am not looking to generate a csv file, I just wanted to create a string of csv that I send as text to the user.

推荐答案

这里的代码我知道对Ruby 1.9.2与Rails 3.0.1工作

Here is code I know works against Ruby 1.9.2 with Rails 3.0.1

def export_csv(filename, header, rows)
    require 'csv'

    file = CSV.generate do |csv|
        csv << header if not header.blank?
        rows.map {|row| csv << row}
    end

    send_data file, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment;filename=#{filename}.csv"
end

这篇关于Ruby 1.9.2导出CSV字符串而不生成文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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