ruby-on-railsrubyzipunziprubyzip

NameError - uninitialized constant Zip


I am trying to unzip a file in my Spree plugin.

Defined the unzipping method in a module which looks like this.

module ImportImages
  class Zipper
    def self.unzip(zip, unzip_dir, remove_after = false)
      Zip::File.open(zip) do |zip_file|
        zip_file.each do |f|
          f_path=File.join(unzip_dir, f.name)
          FileUtils.mkdir_p(File.dirname(f_path))
          zip_file.extract(f, f_path) unless File.exist?(f_path)
        end
      end
      FileUtils.rm(zip) if remove_after
    end
  end
end

I have included the rubyzip gem in my Gemfile.

gem 'rubyzip'
gem 'zip-zip'

When trying to run it, I am getting the following error.

NameError - uninitialized constant ImportImages::Zipper::Zip:

I have tried every solution provided in stackoverflow and other sites. I tried downgrading the version of rubyzip which is 1.2.0 now and add require 'zip' or require 'zip/zip'. Both returned load error.

I have try adding require 'zip/filesystem' to the class. But got

LoadError - cannot load such file -- zip/zipfilesystem

Any solution for this?


Solution

  • It's looking for a nested Constant. Change line Zip::File.open(zip) do |zip_file| with below:

    ::Zip::File.open(zip) do |zip_file|
    

    It should work. Also make sure you require rubygem/bundle setup. Though in spree it should've already been done.