damuz91
damuz91

Reputation: 1738

Paperclip + S3 massive zipping

If you got Paperclip + AWS S3 working in your rails 3 application and you want to zip attachments related to a model how to proceed?

Upvotes: 1

Views: 633

Answers (1)

damuz91
damuz91

Reputation: 1738

Note: Some questions at stackoverflow are outdated, some paperclip methods are gone.

Lets say we got a User and it :has_many => user_attachments

GC.disable
@user = User.find(params[:user_id])
zip_filename = "User attachments - #{@user.id}.zip" # the file name
tmp_filename = "#{Rails.root}/tmp/#{zip_filename}" # the path
Zip::ZipFile.open(tmp_filename, Zip::ZipFile::CREATE) do |zip|
  @user.user_attachments.each { |e| 
    attachment = Paperclip.io_adapters.for(e.attachment) #has_attached_file :attachment (,...)
    zip.add("#{e.attachment.original_filename}", attachment.path)
  }
end
send_data(File.open(tmp_filename, "rb+").read, :type => 'application/zip', :disposition => 'attachment', :filename => zip_filename)
File.delete tmp_filename
GC.enable
GC.start

The trick is to disable the GC in order to avoid Errno::ENOENT exception. The GC will delete the downloaded attachment from S3 before it gets zipped.

Sources:
to_file broken in master?
io_adapters.for(object.attachment).path failing randomly

Upvotes: 4

Related Questions