|
62 | 62 | ```ruby
|
63 | 63 | require 'rubygems'
|
64 | 64 | require 'zip'
|
| 65 | +require 'pathname' |
65 | 66 |
|
66 |
| -directory = '/Users/me/Desktop/directory_to_zip/' |
| 67 | +directory = '/Users/me/Desktop/directory_to_zip' # last slash could be omitted |
67 | 68 | zipfile_name = '/Users/me/Desktop/recursive_directory.zip'
|
68 | 69 |
|
69 |
| -Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| |
70 |
| - Dir[File.join(directory, '**', '**')].each do |file| |
71 |
| - zipfile.add(file.sub(directory, ''), file) |
72 |
| - end |
73 |
| -end |
| 70 | + |
| 71 | +# available options: |
| 72 | +# "directories-skip" - skip directories |
| 73 | +# "directories-recursively" - archive directories recursively |
| 74 | +# "directories-recursively-splat" - archiving should splat directory |
| 75 | +# if so, directory splatting it's content into top-level |
| 76 | + |
| 77 | +options = {"directories-recursively"=>true} |
| 78 | + |
| 79 | +Zip::File.open(archive,Zip::File::CREATE) do |zipfile| |
| 80 | + files.each{ |
| 81 | + |file_to_be_zipped| |
| 82 | + |
| 83 | + if File.directory?(file_to_be_zipped) |
| 84 | + # should skip directories |
| 85 | + next if options["directories-skip"] |
| 86 | + |
| 87 | + # should recursively add directory |
| 88 | + if options["directories-recursively"] |
| 89 | + directory = file_to_be_zipped |
| 90 | + puts "zipper: archiving directory: #{directory}" |
| 91 | + directory_chosen_pathname = options["directories-recursively-splat"] ? directory : File.dirname(directory) |
| 92 | + directory_pathname = Pathname.new(directory_chosen_pathname) |
| 93 | + Dir[File.join(directory, '**', '**')].each do |file| |
| 94 | + file_pathname = Pathname.new(file) |
| 95 | + file_relative_pathname = file_pathname.relative_path_from(directory_pathname) |
| 96 | + zipfile.add(file_relative_pathname,file) |
| 97 | + end |
| 98 | + next |
| 99 | + end |
| 100 | + end |
| 101 | + |
| 102 | + filename = File.basename(file_to_be_zipped) |
| 103 | + |
| 104 | + puts "zipper: archiving #{file_to_be_zipped} as #{filename} into #{zipfile}" |
| 105 | + |
| 106 | + zipfile.add(filename,file_to_be_zipped) |
| 107 | + } |
| 108 | + end |
74 | 109 | ```
|
75 | 110 |
|
76 | 111 | ### Save zip archive entries in sorted by name state
|
|
0 commit comments