Compressing a Folder to a Zip Archive with Ruby

Since downloading a .zip is easier then explaining how to git clone something, i packed my programming pearls in ruby book into a nice little .zip file.

Original folderresulting zip

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

3 thoughts on “Compressing a Folder to a Zip Archive with Ruby

  1. seems to compress all folders in a directory by using installed zip library, definitely fewer LOC, only requires zip is installed.
    Ill give it a try and see if it works…

Leave a comment