Zipping a directory recursively & skip container directory
ruby, ruby-on-rails, rubyzip
Solution
Okay, I solved this on my own. If you are in same boat, here is here how I did it:
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir.chdir directory
Dir.glob("**/*").reject {|fn| File.directory?(fn) }.each do |file|
puts "Adding #{file}"
zipfile.add(file.sub(directory + '/', ''), file)
end
end
This works exactly I want. the limitation here here is that it doesn't handle empty directories. Hopefully, it would help someone.
Problem
Consider, we have following directory structure: ``` Location: /Users/me/Desktop/directory_to_zip/ dir1 dir2 somefile.txt ``` now, If I use rubyzip to zip the contents of `directory_to_zip` using the following code: ``` directory = '/Users/me/Desktop/directory_to_zip/' zipfile_name = '/Users/me/Desktop/recursive_directory.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| Dir[File.join(directory, '**', '**')].each do |file| zipfile.add(file.sub(directory, ''), file) end end ``` This will create a zip file named `recursive_directory.zip`, which will contain a container directory called `directory_to_zip` & inside `directory_to_zip`, will I find my files(`dir1 dir2 somefile.txt`) HOw do I skip creation of `directory_to_zip` inside `recursive_directory.zip`, so that the zip file just contains the contents of `directory_to_zip` & not the directory itself.