lib/zip_dir/zipper.rb in zip_dir-0.1.0 vs lib/zip_dir/zipper.rb in zip_dir-0.1.1
- old
+ new
@@ -1,65 +1,60 @@
+require "zip_dir/zip"
+
module ZipDir
class Zipper
- attr_reader :copy_path, :file
+ attr_reader :copy_path, :filename
- def initialize
- @copy_path = Dir.mktmpdir
- end
+ DEFAULT_FILENAME = "zipper.zip".freeze
- def add_path(source_path)
- FileUtils.cp_r source_path, copy_path
+ def initialize(filename=DEFAULT_FILENAME)
+ @filename = filename
end
- alias_method :<<, :add_path
def generated?
- !!file
+ !!@generated
end
- def generate(filename="zipper")
- yield self
- @file = Zip.new(copy_path, filename).file
+ def generate(source_path=nil, root_directory: false)
+ cleanup if generated?
+
+ @copy_path = Dir.mktmpdir
+ proxy = Proxy.new(copy_path)
+ if source_path
+ raise "should not give block and source_path" if block_given?
+ proxy.add_path source_path, root_directory: root_directory
+ else
+ yield proxy
+ end
+
+ @file = ZipDir::Zip.new(copy_path, filename).file
+ ensure
+ @generated = true
end
+ def file
+ return unless generated?
+ @file
+ end
+
def cleanup
- FileUtils.remove_entry_secure copy_path
+ FileUtils.remove_entry_secure copy_path if copy_path
+ @file = @copy_path = nil
+ @generated = false
end
- class Zip
- attr_reader :source_path
- def initialize(source_path, filename)
- @source_path, @file = source_path, Tempfile.new([filename, ".zip"])
+ class Proxy
+ def initialize(copy_path)
+ @copy_path = copy_path
end
- def file
- generate unless generated?
- @file
- end
-
- def generate
- ::Zip::File.open(@file.path, ::Zip::File::CREATE) do |zip_io|
- zip_path(zip_io)
+ def add_path(source_path, root_directory: false)
+ if root_directory
+ Dir.glob("#{source_path}/*").each { |path| add_path(path) }
+ else
+ FileUtils.cp_r source_path, @copy_path
end
- @generated = true
end
-
- def generated?
- !!@generated
- end
-
- def zip_path(zip_io, relative_path="")
- entries = Dir.clean_entries(relative_path.empty? ? source_path : File.join(source_path, relative_path))
- entries.each do |entry|
- relative_entry_path = relative_path.empty? ? entry : File.join(relative_path, entry)
- source_entry_path = File.join(source_path, relative_entry_path)
-
- if File.directory?(source_entry_path)
- zip_io.mkdir relative_entry_path
- zip_path zip_io, relative_entry_path
- else
- zip_io.add relative_entry_path, source_entry_path
- end
- end
- end
+ alias_method :<<, :add_path
end
end
end
\ No newline at end of file