Rails and RubyZip – Create zip file and delete it after download using send_data

We are not using send_file method because it will get deleted before rails actually starts sending it

 

filename = “#{Rails.root}/public/invoices.zip”
temp_file = Tempfile.new(filename)
input_filenames = Dir.entries(“#{Rails.root}/public/Invoices_pdfs”).select {|f| !File.directory? f}
folder = “#{Rails.root}/public/Invoices_pdfs”

begin
#This is the tricky part
#Initialize the temp file as a zip file
Zip::OutputStream.open(temp_file) { |zos| }

#Add files to the zip file as usual
Zip::File.open(temp_file.path, Zip::File::CREATE) do |zipfile|
input_filenames.each do |file|
zipfile.add(file,  File.join(folder, file))
end
end

#Read the binary data from the file
zip_data = File.read(temp_file.path)

#Send the data to the browser as an attachment
#We do not send the file directly because it will
#get deleted before rails actually starts sending it
send_data(zip_data, :type => ‘application/zip’, :filename => “#{Time.now.to_date}”)
ensure
#Close and delete the temp file
temp_file.close
temp_file.unlink
FileUtils.rm_rf(Dir.glob(“#{Rails.root}/public/Invoices_pdfs/*”))
end

Advertisements

Rails and RubyZip – Create zip file and download using send_file

def make_zip

# Path where your pdfs are situated (‘my_pdf’ is folder with pdfs)
folder = “#{Rails.root}/public/my_pdfs”
input_filenames = Dir.entries(“#{Rails.root}/public/my_pdfs”).select {|f| !File.directory? f}

zipfile_name = “#{Rails.root}/public/myfirstzipfile.zip”

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
input_filenames.each do |filename|
# Two arguments:
# – The name of the file as it will appear in the archive
# – The original file, including the path to find it
zipfile.add(filename,  File.join(folder, filename))
end
zipfile.get_output_stream(“success”) { |os| os.write “All done successfully” }
end
send_file(File.join(“#{Rails.root}/public/”, ‘myfirstzipfile.zip’), :type => ‘application/zip’, :filename => “#{Time.now.to_date}.zip”)
# Remove content from ‘my_pdfs’ folder if you want
FileUtils.rm_rf(Dir.glob(“#{Rails.root}/public/my_pdfs/*”))

end

Prevent submit event of remote => ‘true’ Rails form which open in Modal

We can not directly prevent the form which submit using remote => true

This example show how to prevent submit event of ajax  form which open in modal

$(".modal-form").live("ajax:before",function(evt,data,status,xhr){
   var checked = $(".project-modal-form input:checked").length > 0
   if (!checked){
     $("#warning_notification-project-modal").text("Warning.").slideDown(70         0).delay(7000).slideUp(700);
     $('#warning_notification-project-modal').removeClass('hide')
     return false; 
   }else{
      return true;
     }
});