module Grizzled::FileUtil::ZipUtil::UnzipMixin
UnzipMixin
provides convenient front-end methods for unzipping
files; it uses the 'rubyzip' gem under the covers, so you must have
'rubyzip' installed to use this class. Mixing this module into your
class mixes in methods that will allow you to unzip zip files. Related
modules and classes:
- Grizzled::FileUtil::Zipper
-
A class that includes this module and can be instantiated by itself.
- Grizzled::FileUtil::ZipMixin
-
A module mixin for zipping zip files.
- Grizzled::FileUtil::Unzipper
-
A class that includes `UnzipMixin' and can be instantiated by itself.
Public Instance Methods
Unzips a zip file into a directory.
Parameters:
- zip_file
-
The zip file to unzip.
- directory
-
The directory into which to unzip the file. The directory is created if it doesn't already exist.
- options
-
Options hash, as described below.
- select
-
If a block (
select
) is given, thenunzip
passes each zip file entry name to the block and only unzips the entry if the block returnstrue
. If no block is given, then everything is unzipped (subject also tothe +:recursive+ option, below).
Options:
*NOTE*: Options are symbols (e.g.,
:recursive
).
- recursive
-
If
false
, only extract the top-level files from the zip file. Iftrue
(the default), recursively extract everything. - overwrite
-
If
false
(the default), do not overwrite existing files in the directory. Iftrue
, overwrite any existing files in the directory with extracted zip files whose names match.
Example:
import 'grizzled/fileutil/ziputil' import 'tmpdir' include Grizzled::FileUtil::ZipUtil Dir.mktmpdir do |d| unzip zipfile_path, d # muck with unpacked contents end
# File lib/grizzled/fileutil/ziputil.rb, line 205 def unzip(zip_file, directory, options = {}, &select) overwrite = options.fetch(:overwrite, false) recurse = options.fetch(:recursive, true) zip = Zip::ZipFile.open(zip_file) Zip::ZipFile.foreach(zip_file) do |entry| file_path = File.join(directory, entry.to_s) parent_dir = File.dirname file_path if recurse or (parent_dir == '.') or (parent_dir == '') # If the caller supplied a block, only extract the file if # the block says we can. extract = block_given? ? select.call(path) : true if extract if parent_dir != '' if not File.exists? parent_dir FileUtils::mkdir_p parent_dir end end end end zip.extract(entry, file_path) end end
Call a given block with the list of entries in a zip file, without extracting them.
Parameters:
- zip_file
-
The zip file to unzip.
- block
-
Block to execute on each entry. If omitted, an Enumerator is returned. The block receives a string representing the path of the item in the file.
# File lib/grizzled/fileutil/ziputil.rb, line 238 def zip_file_entries(zip_file, &block) if not block_given? a = [] end Zip::ZipFile.foreach(zip_file) do |entry| if block_given? block.call(entry.to_s) else a << entry.to_s end end if not block_given? return a.each end end