gpt4 book ai didi

ruby - 通过 Ruby 中的 Tempfile 写入文件

转载 作者:数据小太阳 更新时间:2023-10-29 07:41:21 24 4
gpt4 key购买 nike

我有以下后台作业写入 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 文件的代码。我目前收到一个 TypeError,提示“无法将 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

最佳答案

问题是您实际上并未将 csv 数据写入文件。您正在将数组发送到文件句柄。我相信你需要这样的东西:

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

正确设置 CSV 输出过滤。

关于ruby - 通过 Ruby 中的 Tempfile 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14564222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com