Say you're submitting some pictures of kitchen gadgets to Strange Cooks Weekly. You need to zip up your images before sending them, and you're contractually obligated to use Ruby to do it. Here's how.
require 'rubygems'
require 'zip/zip'
puts "Zipping files!"
file_path = "Users/me/Pictures/kitchen_implements"
file_list = ['toast_mitten.png', 'gravy_jug.png', 'biscuit_juicer.png']
zipfile_name = "/Users/me/Desktop/someFile.zip"
Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
file_list.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_path + '/' + filename)
end
end
Note that if the zip file already exists, this script will try to add stuff to it. If you try to add a file that's already in the archive, it will complain.
Thanks a lot dude, your code helped a lot. :)
ReplyDeleteThank you! This was most helpful!
ReplyDelete- Hsoi
its great. I have one small issue:
ReplyDeleteI am trying to zip content from server. Content is something like this
http://myApplication.s3.amazonaws.com/xxxxxxxx/image/image1.jpeg, http://myApplication.s3.amazonaws.com/xxxxxxxx/image/image2.jpeg, http://myApplication.s3.amazonaws.com/xxxxxxxx/image/image3.jpeg
So in "zipfile.add( attachment.document_file_name, attachment.document.url)", i assigned following values:
document_file_name = image1.jpeg/image2.jpeg/image3.jpeg
document.url = http://myApplication.s3.amazonaws.com/xxxxxxxx/image
Now here I am getting following error:
No such file or directory - http://myApplication.s3.amazonaws.com/xxxxxxxx/image
Is I am doing something wrong? Can someone help me out?
Thanks
http://ganeshprasadsr.blogspot.com/2011/03/zip-multiple-files-and-download-as.html
@tahniyat - I'm not sure about zipping remote files; as far as I know, the files you want to zip need to be in the local file system from Rubyzip's perspective. The blog post you linked appears to be showing how to do this on a server after a file has been uploaded, but I don't quite understand it.
DeleteSorry, but I think StackOverflow would be a better place for your question.
thx Nathan.. any other ruby gem which is used to zip remote files?
Delete@tahniyat - Not that I know of. I imagine you'll need to make it a two-step process: download the files to a local directory (maybe /tmp), then zip them. There are lots of HTTP client gems: see https://www.ruby-toolbox.com/categories/http_clients
DeleteI've used Curb, and heard good things about Excon and Typhoeus. You might compare the documentation and see which looks easiest to understand.