我正在構建一個 CRON 作業,以便每月創建一個 CSV 檔案并將其發送到 API
我的方法如下在 /tmp 檔案夾中生成一個 csv 檔案
def save_csv_to_tmp
f = Tempfile.create(["nb_administrateurs_par_mois_#{date_last_month}", '.csv'], 'tmp')
f << generate_csv
f.close
end
現在,在執行方法中,我必須檢索這個 csv 檔案,但我不知道該怎么做:
def perform(*args)
# creates the csv file in tmp folder
save_csv_to_tmp
# TODO : retreive this csv file and send it to the API
end
uj5u.com熱心網友回復:
您可以執行以下操作(使用 的塊版本Tempfile#create,它會自動關閉并取消鏈接臨時檔案):
def save_csv_to_tmp
Tempfile.create(["nb_administrateurs_par_mois_#{date_last_month}", '.csv'], 'tmp'] do |f|
f << generate_csv
# You might need to call `f.rewind` here
# so that your service object can use the file object right away
yield f if block_given?
end
end
并在執行
def perform(*args)
save_csv_to_tmp do |file|
# Send file to API
SendFileService.new(file: file).call # Or something similar
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497359.html
下一篇:使用強引數創建多條記錄
