代码之家  ›  专栏  ›  技术社区  ›  digitalsanctum

如何使用Rubyzip-lib覆盖现有文件

  •  11
  • digitalsanctum  · 技术社区  · 17 年前

    我正在尝试解压缩一个文件,其中包含目标目录中可能存在或不存在的几个文件。如果文件已存在,默认行为似乎是抛出异常。

    如何解压缩到一个目录并简单地覆盖现有文件?

    这是我的代码:

    begin
      Zip::ZipFile.open(source) do |zipfile|
        dir = zipfile.dir
        dir.entries('.').each do |entry|
          zipfile.extract(entry, "#{target}/#{entry}")
        end
      end
    rescue Exception => e
      log_error("Error unzipping file: #{local_zip}  #{e.to_s}")
    end
    
    4 回复  |  直到 17 年前
        1
  •  18
  •   Ingmar Hamer    16 年前

    第三个(proc)参数用与号指定,这意味着ruby希望它在方法调用后位于{}-Backets中,如下所示:

    zipfile.extract(entry, "#{target}/#{entry}"){ true }
    

    zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
    

        2
  •  15
  •   Greg Campbell    16 年前

    zipfile.extract(entry, "#{target}/#{entry}") { true }
    

    如果你想做一些更复杂的逻辑来以不同的方式处理特定的条目,你可以这样做:

    zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
    

    编辑: 固定答案-正如Ingmar Hamer所指出的,当使用上述语法时,我的原始答案将块作为参数传递。

        3
  •  1
  •   mechanical_meat nazca    17 年前

    require 'rubygems'
    require 'fileutils'
    require 'zip/zip'
    
    def unzip_file(file, destination)
      Zip::ZipFile.open(file) { |zip_file|
       zip_file.each { |f|
         f_path=File.join(destination, f.name)
         if File.exist?(f_path) then
           FileUtils.rm_rf f_path
         end
         FileUtils.mkdir_p(File.dirname(f_path))
         zip_file.extract(f, f_path)
       }
      }
    end
    
    unzip_file('/path/to/file.zip', '/unzip/target/dir')
    

    require 'rubygems'
    require 'fileutils'
    require 'zip/zip'
    
    def unzip_file(file, destination)
      if File.exist?(destination) then
        FileUtils.rm_rf destination
      end
      Zip::ZipFile.open(file) { |zip_file|
       zip_file.each { |f|
         f_path=File.join(destination, f.name)
         FileUtils.mkdir_p(File.dirname(f_path))
         zip_file.extract(f, f_path)
       }
      }
    end
    
    unzip_file('/path/to/file.zip', '/unzip/target/dir')
    

    这是 the original code from Mark Needham :

    require 'rubygems'
    require 'fileutils'
    require 'zip/zip'
    
    def unzip_file(file, destination)
      Zip::ZipFile.open(file) { |zip_file|
       zip_file.each { |f|
         f_path=File.join(destination, f.name)
         FileUtils.mkdir_p(File.dirname(f_path))
         zip_file.extract(f, f_path) unless File.exist?(f_path)
       }
      }
    end
    
    unzip_file('/path/to/file.zip', '/unzip/target/dir')
    
        4
  •  0
  •   yonkeltron    16 年前

    link here 提供了一个很好的例子,我已经验证了它的有效性。只需要添加一个必需的“fileutils”即可。