Ruby 1.9.2 export a CSV string without generating a file

给你一囗甜甜゛ 提交于 2019-12-10 12:44:42

问题


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

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

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 - 

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.


回答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


来源:https://stackoverflow.com/questions/6933283/ruby-1-9-2-export-a-csv-string-without-generating-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!