How do i go about zipping a directory in ruby on rails? I've tried rubyzip without success. I don't need to zip the contents of the dir individually just zip the dir itself.
Asked
Active
Viewed 9,212 times
7
-
What's difficult to figure out? Yarin tried rubyzip, didn't like it. Just wants to zip a directory and needs to know the best way to do it. What's confusing? – Andrew Paul Simmons Apr 11 '16 at 17:42
-
What does it mean to zip a directory, but not its contents? All of the answers zip the directory including the contents, so none of them have addressed the question as asked. – J Edward Ellis Sep 05 '18 at 21:19
2 Answers
14
You are going to have to loop through the items in the directory to add an entry in the compressed file.
def compress(path)
gem 'rubyzip'
require 'zip/zip'
require 'zip/zipfilesystem'
path.sub!(%r[/$],'')
archive = File.join(path,File.basename(path))+'.zip'
FileUtils.rm archive, :force=>true
Zip::ZipFile.open(archive, 'w') do |zipfile|
Dir["#{path}/**/**"].reject{|f|f==archive}.each do |file|
zipfile.add(file.sub(path+'/',''),file)
end
end
end
http://grosser.it/2009/02/04/compressing-a-folder-to-a-zip-archive-with-ruby/
Another way to do it with a command
Dir["*"].each do |file|
if File.directory?(file)
#TODO add OS specific,
# 7z or tar .
`zip -r "#{file}.zip" "#{file}"`
end
end
http://ruby-indah-elegan.blogspot.com/2008/12/zipping-folders-in-folder-ruby-script.html
Update
Thank you Mahmoud Khaled for the edit/update
for the new version use Zip::File.open
instead of Zip::ZipFile.open

Sully
- 14,672
- 5
- 54
- 79
-
1the second way doesn't wok on many hosting environments because they don't include zip.exe in their VM. Heroku for instance doesn't. – baash05 Feb 04 '14 at 22:59
-
But what the way are better? To use ruby or zip/gzip utility on production and why? – bmalets Aug 06 '14 at 14:02
-
First one is better, because it is using a Ruby library. The second one just calls zip.exe in a Windows environment – Sully Aug 07 '14 at 11:53
0
You can create an archive of the directory using tar tar -cvf your_dir.tar your_dir/
and then compress the tar in rails using -
def gzip_my_dir_tar(your_dir_tar_file)
content = File.read(your_dir_tar_file)
ActiveSupport::Gzip.compress(content)
end
Its already answered at Rails 3: How do I generate a compressed file on request