Ka Mok
Ka Mok

Reputation: 1988

How to email a self generated csv file in Rails without saving it?

In my Rails application, I create a CSV file using CSV.open block in a model method.

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

In my controller, I have an action that sends the file to a user input email address

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

   JobMailer.send_csv(email).deliver
end

In the JobMailer, I directly refer to the file by file name because the CSV.open block from SomeModel.write_csv saves the file onto disk at the main directory.

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

Currently the app will rewrite over the file when a new request comes in, and I believe when I push to production on Heroku, it will automatically delete it after some time.

To recap:

  1. Generate a CSV
  2. Email it via Mailer
  3. Remove the file

Can this be done without saving it to disk? Is there a better way?

Upvotes: 18

Views: 10200

Answers (1)

Saiqul Haq
Saiqul Haq

Reputation: 2397

You can use CSV#generate class method

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

Upvotes: 44

Related Questions