0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rubyzipで複数ディレクトリを圧縮する

Posted at

rubyzip公式に、再帰的にディレクトリを保存するサンプル(https://github.com/rubyzip/rubyzip)がありました。

ですが、これだと単一ディレクトリしか圧縮できなかったので、複数ディレクトリを保存できるように(ゴリ押しで)改造しました。

ソースコード

require 'zip'

# Usage:
#   directories_to_zip = ["/tmp/input", "/bar/input"]
#   output_file = "/tmp/out.zip"
#   zf = ZipFileGenerator.new(directories_to_zip, output_file)
#   zf.write()
class ZipFileGenerator
  # Initialize with the directory to zip and the location of the output archive.
  def initialize(input_dirs, output_file)
    @input_dirs = input_dirs
    @output_file = output_file
  end

  def write
    @input_dirs.each do |i|
      @input_dir = i
      entries = Dir.entries(@input_dir) - %w[. ..]
      ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |zipfile|
        write_entries entries, @input_dir, zipfile
      end
    end
  end

  private

  def write_entries(entries, path, zipfile)
    entries.each do |e|
      zipfile_path = File.join(path, e)
      disk_file_path = zipfile_path

      if File.readable? disk_file_path
        if File.directory? disk_file_path
          recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
        else
          put_into_archive(disk_file_path, zipfile, zipfile_path)
        end
      end
    end
  end

  def recursively_deflate_directory(disk_file_path, zipfile, zipfile_path)
    zipfile.mkdir zipfile_path
    subdir = Dir.entries(disk_file_path) - %w[. ..]
    write_entries subdir, zipfile_path, zipfile
  end

  def put_into_archive(disk_file_path, zipfile, zipfile_path)
    zipfile.add(zipfile_path, disk_file_path)
  end
end

使い方

第一引数に複数ディレクトリのそれぞれのパスを表す配列と、第二引数にzipの書き込み先を指定すればOKです。

gen = ZipFileGenerator.new(["target1", "target2"], "output.zip")
gen.write

もっとよい書き方があればコメントください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?