4

I am attempting to use rubyzip to create zip archives on the fly in my app. I'm using their readme as a starting point. I added the gem to my Gemfile:

gem 'rubyzip'

Then ran bundle install and restarted the rails server.

My controller code is:

require 'rubygems'
require 'zip'

filename = "#{Time.now.strftime('%y%m%d%H%M%S')}"
input_filenames = ["#{filename}.txt"]
zip_filename = "#{filename}.zip"

Zip::File.open(zip_filename, Zip::File::CREATE) do |zipfile|
  input_filenames.each do |f|
    zipfile.add(f, directory + '/' + f)
  end
end

The error I'm getting is: cannot load such file -- zip

I've tried require 'zip/zip' but it produces the same error.

Thanks in advance!

seancdavis
  • 2,739
  • 2
  • 26
  • 36

3 Answers3

13

You might be looking at an example that's too new.

If you are using Rubyzip 0.9.x, then you need to follow this example:

(require "zip/zip", then use Zip::ZipFile instead of Zip::File)

require 'zip/zip'

folder = "Users/me/Desktop/stuff_to_zip"
input_filenames = ['image.jpg', 'description.txt', 'stats.csv']

zipfile_name = "/Users/me/Desktop/archive.zip"

Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile|
  input_filenames.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, folder + '/' + filename)
  end
end
levinalex
  • 5,889
  • 2
  • 34
  • 48
  • Awesome! This worked perfectly. I am using 0.9.9. Thanks so much for your help. – seancdavis Aug 01 '13 at 12:24
  • Looks like the gem docs are out of date, b/c they have `Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|` but after looking at the source code, `Zip::ZipFile...` is correct. I'll let them know. – Brian Ledsworth Aug 28 '13 at 21:30
5

I suggest you to use:

gem 'rubyzip',  "~> 1.1", require: 'zip'

and then require 'zip' in your controller should work fine.

Robert
  • 5,278
  • 43
  • 65
  • 115
Adam Piotrowski
  • 674
  • 1
  • 7
  • 15
2

Interface of rubyzip was changed. You using old version. Docs on rubydoc.info from master branch.