【问题标题】:How to email a self generated csv file in Rails without saving it?如何在 Rails 中通过电子邮件发送自生成的 csv 文件而不保存它?
【发布时间】:2016-09-18 02:18:30
【问题描述】:

在我的 Rails 应用程序中,我在模型方法中使用 CSV.open 块创建了一个 CSV 文件。

class SomeModel
   def self.write_csv
      CSV.open("my_file_name.csv", "w") do |csv|
         ### inserts lines into the file ###
      end
   end
end

在我的控制器中,我有一个将文件发送到用户输入电子邮件地址的操作

def some_controller_method
   SomeModel.write_csv
   email = params[:email]

   JobMailer.send_csv(email).deliver
end

JobMailer 中,我直接按文件名引用文件,因为SomeModel.write_csv 中的CSV.open 块将文件保存到磁盘的主目录中。

def send_csv(email)
    attachments['my_file_name.csv'] = {mime_type: 'text/csv', content: File.read(Rails.root.join('your_file.csv'))}
    mail(to: email, subject: 'My subject', body: 'My body.')
end

目前应用程序会在收到新请求时重写文件,我相信当我在 Heroku 上推送到生产环境时,它会在一段时间后自动删除它。

回顾一下:

  1. 生成 CSV
  2. 通过 Mailer 发送电子邮件
  3. 删除文件

可以在不将其保存到磁盘的情况下完成此操作吗?有没有更好的办法?

【问题讨论】:

  • 您在哪个文件中编写了“CSV.open”代码?

标签: ruby-on-rails csv heroku


【解决方案1】:

你可以使用 CSV#generate 类方法

class SomeModel
   def self.generate_csv
      CSV.generate do |csv|
         ### inserts lines into the file ###
      end
   end
end

def some_controller_method
   csv = SomeModel.generate_csv
   email = params[:email]

   JobMailer.send_csv(email, csv).deliver
end

def send_csv(email, csv)
    attachments['my_file_name.csv'] = {mime_type: 'text/csv', content: csv}
    mail(to: email, subject: 'My subject', body: 'My body.')
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2013-08-04
    • 2011-03-21
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多