Module: Omnizip::Archive

Defined in:
lib/omnizip/archive.rb,
lib/omnizip/archive/builder.rb,
lib/omnizip/archive/reader_session.rb

Overview

High-level block-style archive facade over the registered ArchiveHandlers. This is the API the guides document:

Omnizip::Archive.create('backup.7z', format: :seven_zip,
                      level: 9) do |archive|
archive.add_file('report.pdf', 'reports/report.pdf')
archive.add_directory('photos/')
archive.add_data('notes/readme.txt', "generated\n")
end

Omnizip::Archive.open('backup.7z') do |archive|
archive.entries.each { |e| puts "#{e.name} (#{e.size})" }
archive.read('notes/readme.txt')
archive.extract_all('output/')
end

The format is resolved from the output path's extension when format: is not given explicitly, exactly like the convenience methods. Passwords are supported for 7z only (ZIP writing and reading have no encryption support); asking for one elsewhere raises rather than silently producing an unprotected archive.

Defined Under Namespace

Classes: Builder, Entry, ReaderSession

Class Method Summary collapse

Class Method Details

.create(path, format: Convenience::DEFAULT_FORMAT, **options, &block) ⇒ Object

Create an archive, yielding a Builder that translates the documented +add_file+/+add_directory+/+add_data+ calls onto the resolved handler. Returns the archive path.



46
47
48
49
50
51
52
53
54
# File 'lib/omnizip/archive.rb', line 46

def create(path, format: Convenience::DEFAULT_FORMAT, **options, &block)
  resolved = Omnizip.resolve_archive_format(path, format)
  check_password_support!(resolved, options[:password])

  Omnizip::ArchiveHandler.for(resolved).create(path, **options) do |proxy|
    block&.call(Builder.new(proxy))
  end
  path
end

.open(path, password: nil, **options) {|session| ... } ⇒ Object

Open an archive for reading, yielding a ReaderSession. Without a block, returns the session. An explicit password: wins over ENV.

Yields:

  • (session)


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/omnizip/archive.rb', line 59

def open(path, password: nil, **options, &block)
  resolved = Omnizip.resolve_archive_format(
    path, Convenience::DEFAULT_FORMAT, writing: false
  )
  pw = password || ENV.fetch("OMNIZIP_PASSWORD", nil)
  check_password_support!(resolved, pw)

  options[:password] = pw if pw
  session = ReaderSession.new(
    Omnizip::ArchiveHandler.for(resolved), path, options
  )
  return session unless block

  yield session
end