views:

13

answers:

2

I am attempting to generate a CSV file. Everything is fine except for blank fields, I'm not quite sure have "" instead of actual quotes. I've provided the code I'm using to generate the file and some output.

<% headers = ["Username", "Name", "E-mail", "Phone Number"] %>
<%= CSV.generate_line headers %>

<% @users_before_paginate.each do |user| %>
  <% row = [ "#{user.username}".html_safe ] %>
  <% row << "#{user.profile.first_name} #{user.profile.last_name}".html_safe unless user.profile.blank? %>
  <% row << "#{user.email}".html_safe unless user.profile.nil? %>
  <% row << "#{user.profile.phone}".html_safe unless user.profile.nil? %>
  <%= CSV.generate_line row %>
<% end %>

Output

Username,Name,E-mail,Phone Number

  admin,LocalShopper ,[email protected],&quot;&quot;
  Brian,Oliveri Design ,[email protected],727-537-9617
  LocalShopperJenn,Jennifer M Gentile ,[email protected],&quot;&quot;
+2  A: 

Instead of calling html_safe on each part of the array and then making a new (non-html-safe) string from it, try calling it at the end, after the string is returned from generate_line:

<%= CSV.generate_line(row).html_safe %>
Andrew Vit
A: 

Here's a template I've used that works well enough:

<%=
  response.content_type = 'application/octet-stream'

  FasterCSV.generate do |csv|
    csv << @report[:columns]
    @report[:rows].each do |row|
      csv << row
    end
  end
%>

You can do this entirely within the controller if you like and render it as type :text instead.

It also helps if you wrangle the content into order, in this case a simple @report hash, inside the controller than to do all the heavy lifting in the view.

tadman