首页 > 解决方案 > 在构建 zip 文件时,如何调整 RubyZip 示例以使用 File.write_buffer 而不是 File.open?

问题描述

在构建 zip 文件时,如何调整使用 File.open 的以下示例以使用 write_buffer 而不是 File.open,如下一个代码示例中给出的那样?

这是 File.open 示例:

require 'zip'

# This is a simple example which uses rubyzip to
# recursively generate a zip file from the contents of
# a specified directory. The directory itself is not
# included in the archive, rather just its contents.
#
# Usage:
#   directoryToZip = "/tmp/input"
#   outputFile = "/tmp/out.zip"
#   zf = ZipFileGenerator.new(directoryToZip, outputFile)
#   zf.write()
class ZipFileGenerator

  # Initialize with the directory to zip and the location of the output archive.
  def initialize(inputDir, outputFile)
    @inputDir = inputDir
    @outputFile = outputFile
  end

  # Zip the input directory.
  def write()
    entries = Dir.entries(@inputDir); 
    entries.delete("."); 
    entries.delete("..")
    io = Zip::File.open(@outputFile, Zip::File::CREATE);

    writeEntries(entries, "", io)
    io.close();
  end



  # A helper method to make the recursion work.
  private
  def writeEntries(entries, path, io)

    entries.each { |e|
      zipFilePath = path == "" ? e : File.join(path, e)
      diskFilePath = File.join(@inputDir, zipFilePath)
      puts "Deflating " + diskFilePath
      if  File.directory?(diskFilePath)
        io.mkdir(zipFilePath)
        subdir =Dir.entries(diskFilePath); subdir.delete("."); subdir.delete("..")
        writeEntries(subdir, zipFilePath, io)
      else
        io.get_output_stream(zipFilePath) { |f| 
f.puts(File.open(diskFilePath, "rb").read())}
      end
    }
  end
end 

这是我希望上面的代码适应的 write_buffer 示例:

buffer = Zip::OutputStream.write_buffer do |out|
  @zip_file.entries.each do |e|
    unless [DOCUMENT_FILE_PATH, RELS_FILE_PATH].include?(e.name)
      out.put_next_entry(e.name)
      out.write e.get_input_stream.read
     end
  end

  out.put_next_entry(DOCUMENT_FILE_PATH)
  out.write xml_doc.to_xml(:indent => 0).gsub("\n","")

  out.put_next_entry(RELS_FILE_PATH)
  out.write rels.to_xml(:indent => 0).gsub("\n","")
end

File.open(new_path, "wb") {|f| f.write(buffer.string) }

在此先感谢您的帮助。这是我的适应尝试,但我感到迷茫。

def writeViaBuffer()
    entries = Dir["#{@inputDir}/**/*"]; entries.delete("."); entries.delete("..")
    buffer = Zip::OutputStream.write_buffer do |out|
     entries.each do |e|
       byebug
       @file = nil
       @data = nil
       if !File.directory?(e)
         @file = File.open(e, "r+b")
         @data = @file.read


         unless [@outputFile, @inputDir].include?(e)
           out.put_next_entry(e)
           out.write @data
         end
         @file.close
       end
   end

   out.put_next_entry(@outputFile)
   out.write xml_doc.to_xml(:indent => 0).gsub("\n","")

   out.put_next_entry(@inputDir)
   out.write rels.to_xml(:indent => 0).gsub("\n","")
   end

   File.open(new_path, "wb") {|f| f.write(buffer.string) }  
 end

标签: rubyruby-on-rails-5rubyzip

解决方案


推荐阅读