Ruby, Tempfile, Writing to csv

I have a background job that writes to a csv file and sends it via email. I am using the Tempfile class, so the file is deleted after I send it to the user. Currently when I look at the csv file the results are like this:

["Client Application"    "Final Price"   "Tax"   "Credit"    "Base Price"    "Billed At"     "Order Guid"    "Method of Payment Guid"    "Method of Payment Type"]
["web"   nil     nil     nil     nil     nil     nil     "k32k313k1j3"   "credit card"]

      

Please ignore the data, but the problem is that it writes directly to the file in ruby ​​format and does not remove the "" and [] characters ...

See the code below:

class ReportJob
@queue = :report_job

 def self.perform(client_app_id, current_user_id)
  user = User.find(current_user_id)
  client_application = Application.find(client_app_id)
  transactions = client_application.transactions
  file = Tempfile.open(["#{Rails.root}/tmp/", ".csv"]) do |csv|
    begin
     csv << ["Application", "Price", "Tax", "Credit", "Base Price", "Billed At", "Order ID", "Payment ID", "Payment Type"]
     transactions.each do |transaction|
      csv << "\n"
      csv << [application.name, transaction.price, transaction.tax, transaction.credit, transaction.base_price, transaction.billed_at, transaction.order_id, transaction.payment_id, transaction.payment_type]
    end
   ensure
    ReportMailer.send_rev_report(user.email, csv).deliver
    csv.close(unlink_now=false)
    end
  end
end

end

      

Would there be a problem using the tempfile class instead of the csv class? or can I do something to change the way I write to the file? Any help is appreciated. Thank!

Add code to read the csv file in the mailbox. I am currently getting a TypeError that says "Unable to convert CSV to String".

class ReportMailer < ActionMailer::Base
 default :from => "test@gmail.com"

  def send_rev_report(email, file)
     attachments['report.csv'] = File.read("#{::Rails.root.join('tmp', file)}")
      mail(:to => email, :subject => "Attached is your report")
    end
  end
end

      

+3


source to share


3 answers


The problem is that you are not actually writing the csv data to the file. You are sending arrays to a file descriptor. I believe you want something like:

Tempfile.open(....) do |fh|
    csv = CSV.new(fh, ...)
    <rest of your code>
end

      



to properly configure filtering of the CSV output.

+10


source


try this:



Tempfile.open(["#{Rails.root}/tmp/", ".csv"]) do |outfile|
  CSV::Writer.generate(outfile) do |csv|
    csv << ["Application", "Price", "Tax", "Credit", "Base Price", "Billed At", "Order ID", "Payment ID", "Payment Type"]
    #...
  end
end

      

+1


source


I prefer to do

tempfile = Tempfile.new(....)
csv = CSV.new(tempfile, ...) do |row|
  <rest of your code>
end

      

0


source







All Articles