开发者

Ruby 1.9.2 export a CSV string without generating a file

开发者 https://www.devze.com 2023-03-25 06:57 出处:网络
I just can\'t get the \'To a String\' example under \'Writing\' example in the documentation to work at all.

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_s开发者_开发问答tring = 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消