Last active
March 17, 2016 03:28
-
-
Save pepesenaris/72b3e20d0645341f02a8 to your computer and use it in GitHub Desktop.
Rails temp zip response example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#helper method to generate temp zip file | |
def generate_temp_zip_file(base_name, items) | |
tmpfile = Tempfile.new([base_name, '.zip'], 'tmp') | |
Zip::ZipOutputStream.open(tmpfile) {|zop|} #Necessary to create empty zip | |
Zip::ZipFile.open(tmpfile.path, Zip::ZipFile::CREATE) do |zip_file| | |
items.each do |entry| | |
zip_file.add(entry[:name], entry[:src_path]) | |
end | |
end | |
begin | |
yield tmpfile | |
rescue Exception => e | |
Rails.logger.error("TEMP ZIP FILE ERROR #{e.message}") | |
ensure | |
tmpfile.unlink | |
tmpfile.close | |
end | |
end | |
#Some notes..... | |
#The version of rubyzip used here (0.9.9 i think) is not the latest of rubyzip | |
#some minor changes may be needed to use the latest version | |
#but the overall process is the same | |
def some_action | |
filename = "some_path_for_the_zip_file.zip" | |
entries = [{name: "a", src_path: "path/to/file/in/hdd"}] | |
generate_temp_zip_file(File.basename(filename, '.zip'), entries) do |tmpfile| | |
send_file(tmpfile.path, filename: File.basename(filename)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment