Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Rails from encoding entities in FasterCSV output

I'm using FasterCSV to produce CSV output of my reports in a Rails 3 application. Here's a code snippet:

<%= FasterCSV.generate do |csv|
  @groups.each do |b|
    record = [ b.group, b.organization_name, b.status, b.comments ]
    csv << record
  end
end 
%>

When FasterCSV includes an empty string, it uses a pair of empty double quotes.

Unfortunately, Rails 3 is encoding those quotation marks as entities, which doesn't work very well with Excel. Here's what my CSV output looks like (when b.comments is nil or an empty string):

Rafeland,Rafe Organization,Submitted,&quot;&quot;

What's the generally accepted method for preventing Rails from encoding those entities? I know about the raw method, but it doesn't take a block that I can put the CSV generation into.

like image 944
Rafe Avatar asked Dec 06 '25 18:12

Rafe


1 Answers

I would recommend generating a file (perhaps merely a Tempfile) and serving that, but if you want to continue doing it your way, then you need to tell Rails that the entire CSV is HTML-safe. Assuming FasterCSV.generate returns a normal String, then simply tack on html_safe:

<%= FasterCSV.generate do |csv|
  ...
end.html_safe
%>
like image 173
Jeremy Weathers Avatar answered Dec 08 '25 06:12

Jeremy Weathers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!