Class: Struggle::ZipTool

Inherits:
Object
  • Object
show all
Defined in:
lib/struggle/zip_tool.rb

Class Method Summary collapse

Class Method Details

.dir(input_dir, output_file) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/struggle/zip_tool.rb', line 14

def dir(input_dir, output_file)
  @input_dir = input_dir
  @output_file = output_file
  entries = Dir.entries(@input_dir) - %w(. ..)

  ::Zip::File.open(@output_file, ::Zip::File::CREATE) do |io|
    write_entries entries, '', io
  end
end

.file(input_files, output_file) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/struggle/zip_tool.rb', line 24

def file(input_files, output_file)
  Zip::File.open(output_file, Zip::File::CREATE) do |zipfile|
    if input_files.class == Array
      input_files.each do |filename|
        idex = filename.rindex("/")
        if idex
          zipfile.add(filename[idex+1, filename.length-idex], filename)
        else
          zipfile.add(filename, filename)
        end
      end
    elsif input_files.class == String
      idex = input_files.rindex("/")
      if idex
        zipfile.add(input_files[idex+1, input_files.length-idex], input_files)
      else
        zipfile.add(input_files, input_files)
      end
    end
  end
end

.put_into_archive(disk_file_path, io, zip_file_path) ⇒ Object



70
71
72
73
74
# File 'lib/struggle/zip_tool.rb', line 70

def put_into_archive(disk_file_path, io, zip_file_path)
  io.get_output_stream(zip_file_path) do |f|
    f.write(File.open(disk_file_path, 'rb').read)
  end
end

.recursively_deflate_directory(disk_file_path, io, zip_file_path) ⇒ Object



64
65
66
67
68
# File 'lib/struggle/zip_tool.rb', line 64

def recursively_deflate_directory(disk_file_path, io, zip_file_path)
  io.mkdir zip_file_path
  subdir = Dir.entries(disk_file_path) - %w(. ..)
  write_entries subdir, zip_file_path, io
end

.write_entries(entries, path, io) ⇒ Object

A helper method to make the recursion work.



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/struggle/zip_tool.rb', line 50

def write_entries(entries, path, io)
  entries.each do |e|
    zip_file_path = path == '' ? e : File.join(path, e)
    disk_file_path = File.join(@input_dir, zip_file_path)
    puts "Deflating #{disk_file_path}"

    if File.directory? disk_file_path
      recursively_deflate_directory(disk_file_path, io, zip_file_path)
    else
      put_into_archive(disk_file_path, io, zip_file_path)
    end
  end
end