In one of app we are sending multiple PDFs as attachment, so instead of sending individual file we decided to send all PDFs in zip. I found a gem 'Rubyzip', to create temporary zip archive and send it as attachment.

Rubyzip is a ruby liabrary to reading and writing zip file.

To create a zip and send it as attachment using Rubyzip here’s a simple example:

  1. Add gem in gemfile

    gem 'rubyzip'
    
  2. Write function to create zip file:

    def get_zip_data
      zip_file = Tempfile.new("example.zip")
      file_names = ['demo1.png', 'temp1.txt', 'temp2.pdf']
      file_path = path_to_files
    
      Zip::File.open(zip_file.path, Zip::File::CREATE) do |zipfile|
        file_names.each do |filename|
          zipfile.add(filename, File.join(file_path, filename))
        end
      end
    
     zip_data = File.read(zip_file.path)
    
     zip_file.close
     zip_file.unlink
     zip_data
    end
    

here we have created temp file with .zip extension. file_names are the files which we want to send in zip archive and file_path is path where these file are present. Then open zip file and add files one by one in zip file.
After adding files in zip our archive is ready to send.
Now read data form created zip archive to send it as attachment then close and unlink the temporary zip file.

For more information read about Rubyzip here.