我有一个后台任务,将数据写入CSV文件并通过电子邮件发送给用户。我使用Tempfile类,所以在将文件发送至用户后会将其删除。目前,当我查看生成的CSV文件时,结果如下:
["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"]
请忽略数据,但问题在于,它以ruby格式直接写入文件,并且没有删除""和[]字符。
请查看以下代码:
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
这是否与使用tempfile类而不是csv类有关?或者我能否做些改变以改变写入文件的方式?
在邮件程序中添加读取csv文件的代码。我目前收到一个类型错误,提示“无法将CSV转换为字符串”。
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