Module: SpatialFeatures::Unzip

Defined in:
lib/spatial_features/unzip.rb

Defined Under Namespace

Classes: PathNotFound

Constant Summary collapse

IGNORED_ENTRY_PATHS =

paths containing ‘__macosx’ or beginning with a ‘.’

/(\A|\/)(__macosx|\.)/i.freeze

Class Method Summary collapse

Class Method Details

.entries(file_path) ⇒ Object



38
39
40
# File 'lib/spatial_features/unzip.rb', line 38

def self.entries(file_path)
  Zip::File.open(File.path(file_path))
end

.extract(file_path, tmpdir: nil, downcase: false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/spatial_features/unzip.rb', line 19

def self.extract(file_path, tmpdir: nil, downcase: false)
  tmpdir ||= Dir.mktmpdir
  [].tap do |paths|
    entries(file_path).each do |entry|
      next if entry.name =~ IGNORED_ENTRY_PATHS
      output_filename = entry.name
      output_filename = output_filename.downcase if downcase
      path = "#{tmpdir}/#{output_filename}"
      FileUtils.mkdir_p(File.dirname(path))
      entry.extract(path)
      paths << path
    end
  end
end

.is_zip?(file) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
# File 'lib/spatial_features/unzip.rb', line 42

def self.is_zip?(file)
  zip = file.readline.start_with?('PK')
  file.rewind
  return zip
rescue EOFError
  return false
end

.names(file_path) ⇒ Object



34
35
36
# File 'lib/spatial_features/unzip.rb', line 34

def self.names(file_path)
  entries(file_path).collect(&:name)
end

.paths(file_path, find: nil, **extract_options) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/spatial_features/unzip.rb', line 8

def self.paths(file_path, find: nil, **extract_options)
  paths = extract(file_path, **extract_options)

  if find = Array.wrap(find).presence
    paths = paths.select {|path| find.any? {|pattern| path.index(pattern) } }
    raise(PathNotFound, "Archive did not contain a file matching #{find}") if paths.empty?
  end

  return Array(paths)
end