How to rename file and directory in a zip file using rubyzip

2k views Asked by At

I'm trying to rename a file and a directory in a zip. I'd tried three different, all not working. What is the right command to do it?

Below is the excerpt of my code:

require 'zip/zip'
...

def renaming_zip(zip_file)
  Zip::ZipFile.open(zip_file).each do |entry|

      if entry.name == "mimetype"
        puts "#{entry.name} is a file ? #{File.file? entry.name}"
        puts " class ? #{entry.class}"
        new_filename = "#{entry.name.gsub("mimetype", "#mimetype-new")}"
        #found_entry = entry.get_entry("mimetype")
        #found_entry.name = new_filename                               #1st try
        puts  " new filename  #{new_filename}"
        #File.rename(entry.name, new_filename)                         #2nd try
        #entry.rename(entry.name, new_filename)                   #3rd try
      end
  end
end

if I execute without any renaming trial command, I get this output, so you can see the file exists in the zip. It's just not a File class, but a Zip::ZipEntry class, and I'm able to parse the new name.

mimetype is a file ? false
class ? Zip::ZipEntry
new filename  #mimetype-new

with 1st try (uncommented), I get this error:

mimetype is a file ? false
class ? Zip::ZipEntry
Uncaught exception: undefined method `get_entry' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:45:in `block in renaming_zip'
...

with 2nd try (uncommented), I get this error:

Uncaught exception: No such file or directory - (mimetype, #mimetype-new)
/Users/.../app/lib/zip_rename.rb:48:in `rename'
/Users/.../app/lib/zxp_rename.rb:48:in `block in renaming_zip'
...
mimetype is a file ? false
class ? Zip::ZipEntry
new filename  #mimetype-new

with 3rd try( uncommented), I get this error:

mimetype is a file ? false
class ? Zip::ZipEntry
new filename  #mimetype-new
Uncaught exception: undefined method `rename' for mimetype:Zip::ZipEntry
/Users/.../app/lib/zip_rename.rb:49:in `block in renaming_zip'
    ...
2

There are 2 answers

0
Yuri Karpovich On

To rename file inside zip with rubyzip:

require 'zip'

old_name = 'mimetype'
new_filename = '#mimetype-new'

Zip::ZipFile.open(zip_file_path).each do |zipfile|
  files = zipfile.select(&:file?)
  file = files.find{|f| f.name == old_name}
  zipfile.rename(file.name, new_filename) if file
end
0
Sully On

To rename the entry call rename on the entry.

1st Attempt fails because you are calling get_entry on entry, it should be on ZipFile.

2nd Attempt fails because the code ends the string with double-quotes.

new_filename = entry.name.gsub('mimetype', '#mimetype-new')

3rd Attempt fails because the object is mimetype:Zip::ZipEntry and is not Zip::ZipEntry

The correct way to do it is

new_filename = "#mimetype-new"

Zip::ZipFile.open(zip_file).each do |zipfile|
   files = zipfile.select(&:file?)
   files.each do |file|
      if entry.name == "mimetype"
        entry.rename(entry.name, new_filename)
      end
   end
end