title: Writing to a file via Tempfile in Ruby
body: <p>I have the below background job that writes to a csv file and emails it out. I am using the Tempfile class so the file is removed after I email it to the user. Currently, when I look at the csv file I am producing the results look like the following:</p>
  
  <pre><code>["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"]
  </code></pre>
  
  <p>Please ignore the data, but the issue is, it is being written directly to the file in the ruby format and not removing the "" and [] characters.</p>
  
  <p>Please see the code below:</p>
  
  <pre><code>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 &lt;&lt; ["Application", "Price", "Tax", "Credit", "Base Price", "Billed At", "Order ID", "Payment ID", "Payment Type"]
       transactions.each do |transaction|
        csv &lt;&lt; "\n"
        csv &lt;&lt; [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
  </code></pre>
  
  <p>Would this be an issue with using the tempfile class instead of the csv class? or is there something I could do to change the way it is being written to the file?</p>
  
  <p>Adding the code for reading the csv file in the mailer. I am currently getting a TypeError that says "can't convert CSV into String".</p>
  
  <pre><code>class ReportMailer &lt; ActionMailer::Base
   default :from =&gt; "test@gmail.com"
  
    def send_rev_report(email, file)
       attachments['report.csv'] = File.read("#{::Rails.root.join('tmp', file)}")
        mail(:to =&gt; email, :subject =&gt; "Attached is your report")
      end
    end
  end
  </code></pre>