Class: Omnizip::ArchiveHandlers::ZipHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/omnizip/archive_handlers/zip_handler.rb

Overview

Adapter that exposes the canonical +create+/+open+/+extract_to+ /+list+ interface for the ZIP format. Wraps Omnizip::Zip::File.

Instance Method Summary collapse

Instance Method Details

#add_entry(path, entry_name, source_path) ⇒ Object



62
63
64
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 62

def add_entry(path, entry_name, source_path)
  Omnizip::Zip::File.open(path) { |zip| zip.add(entry_name, source_path) }
end

#create(path, &block) ⇒ Object



8
9
10
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 8

def create(path, &block)
  Omnizip::Zip::File.create(path, &block)
end

#extract_to(path, output_dir, overwrite: false, **_) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 16

def extract_to(path, output_dir, overwrite: false, **_)
  extracted = []
  Omnizip::Zip::File.open(path) do |zip|
    zip.each do |entry|
      dest_path = ::File.join(output_dir, entry.name)
      on_exists = if overwrite
                    proc { true }
                  else
                    proc { |_e, p| raise "File exists: #{p}" }
                  end
      zip.extract(entry, dest_path, &on_exists)
      extracted << dest_path
    end
  end
  extracted
end

#list(path, details: false, **_) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 33

def list(path, details: false, **_)
  Omnizip::Zip::File.open(path) do |zip|
    if details
      zip.entries.map do |entry|
        {
          name: entry.name,
          size: entry.size,
          compressed_size: entry.compressed_size,
          compression_method: entry.compression_method,
          crc: entry.crc,
          time: entry.time,
          directory: entry.directory?,
        }
      end
    else
      zip.names
    end
  end
end

#open(path, &block) ⇒ Object



12
13
14
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 12

def open(path, &block)
  Omnizip::Zip::File.open(path, &block)
end

#read_entry(path, entry_name) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 53

def read_entry(path, entry_name)
  Omnizip::Zip::File.open(path) do |zip|
    entry = zip.get_entry(entry_name)
    raise Errno::ENOENT, "Entry not found: #{entry_name}" unless entry

    zip.read(entry)
  end
end

#remove_entry(path, entry_name) ⇒ Object



66
67
68
# File 'lib/omnizip/archive_handlers/zip_handler.rb', line 66

def remove_entry(path, entry_name)
  Omnizip::Zip::File.open(path) { |zip| zip.remove(entry_name) }
end