Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape Comma from CSV in Ruby

I'm creating a CSV download in my Ruby application which has some Dollar amount fields. These fields has data in cyrrency format like $35,456 and when such data comes in CSV it get seperated into two fiedls , data after comma moved to next column in CSV.

Here is my code to render CSV

Sell Date, Sell Amount
- @rows.each do |row|
  = "#{row[0]},#{number_to_currency(row[1], :precision => 2)}"

Here is the action used to return CSV

def fifolog
  @rows = Report.fifolog()
respond_to do |format|
  format.csv { render csv: {:rows =>@rows }}
end
end

Is there any escape character i can use to escape "," in ruby

thanks

like image 391
Anil D Avatar asked Sep 07 '12 12:09

Anil D


1 Answers

Use Ruby's built-in to_csv method.

If you haven't already done so, you'll need to require 'csv'.

Sell Date, Sell Amount
- @rows.each do |row|
  = [ row[0], number_to_currency(row[1], :precision => 2) ].to_csv( row_sep: nil ).html_safe

to_csv is available right on the Array and does all the escaping you'd expect it to do.

row_sep: nil prevents the \n at the end of each row since you're already doing that with each. Try it without that and you'll see that you get an extra blank line. If you were just generating a single CSV string then you'd need to keep the \n to separate the rows.

html_safe prevents the " characters from showing up in your CSV file.

That should do it!

JP

like image 137
Joshua Pinter Avatar answered Sep 23 '22 04:09

Joshua Pinter