I want to compress some files in Ruby on Rails and save the zip file in the tmp folder. I’ve got a Document model which has a name field with an associated uploader. I’m also using Carrierwave to upload files to Amazon S3. I’ve got the following code:
class Document < ActiveRecord::Base
mount_uploader :name, DocumentUploader
...
end
def create_zip
documents = Document.all
folder = "#{Rails.root}/tmp"
tmp_filename = "#{folder}/export.zip"
zip_path = tmp_filename
Zip::ZipFile::open(zip_path, true) do |zipfile|
documents.each do |photo|
zipfile.get_output_stream(document.name.identifier) do |io|
io.write document.name.file.read
end
end
end
end
This creates an export.zip file in my tmp folder, but when I try to open it, Archive Manager (Mac OS X) begins unarchiving it, but keeps doing it so without ever finishing. I believe there’s something missing from my code. The zip file size does make sense to me, but I’ve got that problem. Any thoughts? Thanks!
Actually, I found out I could open the zip file using other program (zipeg). However, only the last file from the documents array was in the compressed file. I believe I had been overwriting previous files, as the only remaining file was called the same (export, as the name of the zip itself) in all cases.
The code bellow works for me: