class NdrImport::File::Zip

This class is a zip file handler that returns tables from the extracted files.

Public Class Methods

new(filename, format, options = {}) click to toggle source
Calls superclass method NdrImport::File::Base::new
# File lib/ndr_import/file/zip.rb, line 11
def initialize(filename, format, options = {})
  super
  @pattern = options['pattern'] || //
  @unzip_path = options['unzip_path']

  validate_unzip_path_is_safe!
end

Public Instance Methods

files(&block) click to toggle source
# File lib/ndr_import/file/zip.rb, line 19
def files(&block)
  fail 'Not allowed in external environment' if defined?(::Rails) && ::Rails.env.external?

  return enum_for(:files) unless block

  destination = @unzip_path.join(Time.current.strftime('%H%M%S%L'))
  FileUtils.mkdir_p(SafeFile.safepath_to_string(destination))

  ::Zip::File.open(SafeFile.safepath_to_string(@filename)) do |zipfile|
    unzip_entries(zipfile, destination, &block)
  end
end
tables() click to toggle source

Zip files produce files, never tables.

# File lib/ndr_import/file/zip.rb, line 33
def tables
  fail 'Zip#tables should never be called'
end

Private Instance Methods

unzip_entries(zipfile, destination, &block) click to toggle source

Unzip the zip file entry and enumerate over it

# File lib/ndr_import/file/zip.rb, line 40
def unzip_entries(zipfile, destination, &block)
  zipfile.entries.each do |entry|
    # SECURE: TPG 2010-11-1: The path is stripped from the zipfile entry when extracted
    basename = ::File.basename(entry.name)
    next unless entry.file? && basename.match(@pattern)

    unzipped_filename = destination.join(basename)
    zipfile.extract(entry, unzipped_filename)

    unzipped_files(unzipped_filename, &block)
  end
end
unzipped_files(unzipped_filename, &block) click to toggle source

Enumerate over an unzipped file like any other

# File lib/ndr_import/file/zip.rb, line 54
def unzipped_files(unzipped_filename, &block)
  Registry.files(unzipped_filename, @options).each do |filename|
    block.call(filename)
  end
end
validate_unzip_path_is_safe!() click to toggle source
# File lib/ndr_import/file/zip.rb, line 60
def validate_unzip_path_is_safe!
  SafeFile.safepath_to_string(@unzip_path)
end