Skip to content

Instantly share code, notes, and snippets.

@dharshan
Last active February 13, 2025 13:37
Show Gist options
  • Save dharshan/262a93f8306712a38dd99575ed8fd094 to your computer and use it in GitHub Desktop.
Save dharshan/262a93f8306712a38dd99575ed8fd094 to your computer and use it in GitHub Desktop.
Ruby zip a folder - rubyzip
require 'zip'
input_directory = '' # directory to be zipped
zipfile_name = '' # zip-file name
# zip a folder with only files (NO SUB FOLDERS)
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir[File.join(input_directory, '*')].each do |file|
zipfile.add(file.sub(input_directory, ''), file)
end
end
# zip a folder with files and subfolders
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir["#{input_directory}/**/**"].each do |file|
zipfile.add(file.sub(input_directory + '/', ''), file)
end
end
@romanbaitaliuk
Copy link

Found the issue, thanks:)

@sbonifazzi
Copy link

Found the issue, thanks:)

Hi @romanbaitaliuk , I have the same issue, please can you let me know what was the issue?
Many thank for your help

@henrikj242
Copy link

henrikj242 commented Feb 13, 2025

Thanks for this!

In my case, there were some issues with the filenames beginning with "/". Here's what I did to resolve it (adding files only - no sub dirs):

    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      Dir[File.join(input_directory, '*')].each do |file|
        # add(dst_filename, source_file)
        zipfile.add(File.basename(file), file)
      end
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment