Wednesday, May 9, 2012

There are lots of cases in which, the user wants to download his uploaded documents for offline purpose.  So in rails application it is very easy to achieve this task.
I am using dragonfly gem in my application for file handling. To create a zip I uses rubyzip gem. The demo code is as follows:

Consider that you a have table named as photos and you want to send a zip for it.

#to use rubyzip gem you need to first require it in your code
require 'zip/zip'

def download_photos
photos = Photo.find(:all)

#set the zip file name. For now it is under tmp directory of your rails application
zip_name = "#{Rails.root}/tmp/#{Time.now}.zip"


#delete the existing file so that it always creates a fresh file
File.delete(zip_name) if File.exist?(zip_name)

    Zip::ZipFile.open(zip_name, Zip::ZipFile::CREATE) do |zipfile|
      photos.each do |photo|
        unless photo.cover_image_uid.blank?
          begin
            zipfile.add(photo.name, "#{Rails.root}/public/system/dragonfly
                                                      /#{Rails.env}/#{photo.cover_image_uid}")
          rescue Zip::ZipEntryExistsError => e
            logger.info "Unable to add the following screenshot #{photo.name} of
                                   test_case_revision #{tcr.id} into zip file."
          end
        end
      end
    end
    send_file zip_name

end

Use it and complete your task.
Please let me your of doubts\queries.