Module: ZipFileUtils

Defined in:
lib/write_xlsx/zip_file_utils.rb

Class Method Summary collapse

Class Method Details

.each_dir_for(dir_path, &block) ⇒ Object



60
61
62
# File 'lib/write_xlsx/zip_file_utils.rb', line 60

def self.each_dir_for(dir_path, &block)
  each_file_for(dir_path, &block)
end

.each_file_for(path) {|path| ... } ⇒ Object

Yields:

  • (path)


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/write_xlsx/zip_file_utils.rb', line 64

def self.each_file_for(path, &block)
  if File.file?(path)
    yield(path)
    return true
  end
  dir = Dir.open(path)
  file_exist = false
  dir.each do |file|
    next if ['.', '..'].include?(file)

    file_exist = true if each_file_for(path + "/" + file, &block)
  end
  yield(path) unless file_exist
  file_exist
end

.encode_path(path, encode_s) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/write_xlsx/zip_file_utils.rb', line 84

def self.encode_path(path, encode_s)
  return path unless encode_s

  case encode_s
  when 'UTF-8'
    path.toutf8
  when 'Shift_JIS'
    path.tosjis
  when 'EUC-JP'
    path.toeuc
  else
    path
  end
end

.relative(path, base_dir) ⇒ Object



80
81
82
# File 'lib/write_xlsx/zip_file_utils.rb', line 80

def self.relative(path, base_dir)
  path[base_dir.length + 1..path.length] if path.index(base_dir) == 0
end

.unzip(src, dest, options = {}) ⇒ Object

src zip filename dest destination directory options :fs_encoding=



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/write_xlsx/zip_file_utils.rb', line 39

def self.unzip(src, dest, options = {})
  FileUtils.makedirs(dest)
  Zip::InputStream.open(src) do |is|
    loop do
      entry = is.get_next_entry
      break unless entry

      dir = File.dirname(entry.name)
      FileUtils.makedirs(dest + '/' + dir)
      path = encode_path(dest + '/' + entry.name, options[:fs_encoding])
      if entry.file?
        File.open(path, File::CREAT | File::WRONLY | File::BINARY) do |w|
          w.puts(is.read)
        end
      else
        FileUtils.makedirs(path)
      end
    end
  end
end

.zip(src, dest, options = {}) ⇒ Object

src file or directory dest zip filename options :fs_encoding=



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/write_xlsx/zip_file_utils.rb', line 15

def self.zip(src, dest, options = {})
  src = File.expand_path(src)
  dest = File.expand_path(dest)
  FileUtils.rm_f(dest)
  Zip::File.open(dest, Zip::File::CREATE) do |zf|
    if File.file?(src)
      zf.add(encode_path(File.basename(src), options[:fs_encoding]), src)
      break
    else
      each_dir_for(src) do |path|
        if File.file?(path)
          zf.add(encode_path(relative(path, src), options[:fs_encoding]), path)
        elsif File.directory?(path)
          zf.mkdir(encode_path(relative(path, src), options[:fs_encoding]))
        end
      end
    end
  end
  FileUtils.chmod(0o644, dest)
end