Rubyzip lib를 사용하여 기존 파일을 덮어 쓰는 방법
문제
대상 디렉토리에 아직 존재하거나 존재하지 않을 수도있는 여러 파일이있는 파일을 압축하려고합니다. 파일이 이미 존재하는 경우 기본 동작은 예외를 던지는 것 같습니다.
디렉토리를 감금시키고 기존 파일을 간단히 덮어 쓰는 방법은 무엇입니까?
내 코드는 다음과 같습니다.
begin
Zip::ZipFile.open(source) do |zipfile|
dir = zipfile.dir
dir.entries('.').each do |entry|
zipfile.extract(entry, "#{target}/#{entry}")
end
end
rescue Exception => e
log_error("Error unzipping file: #{local_zip} #{e.to_s}")
end
해결책
Extract ()는 옵션 블록 (OnexistsProc)을 사용하여 파일이 이미 존재하는 경우 파일로 무엇을 해야하는지 결정할 수 있습니다. exploy를 쓸어 내고, 예외를 올리려면 true를 반환합니다.
기존 파일을 모두 덮어 쓰고 싶다면 다음을 수행 할 수 있습니다.
zipfile.extract(entry, "#{target}/#{entry}") { true }
특정 항목을 다르게 처리하기 위해 더 복잡한 논리를 수행하려면 다음을 수행 할 수 있습니다.
zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
편집하다: 고정 답변 - Ingmar Hamer가 지적한 바와 같이, 나의 원래 답변은 위의 구문을 사용할 것으로 예상 될 때 블록을 매개 변수로 전달했습니다.
다른 팁
다른 사람을 구하기 위해 문제를 구하기 위해 :
답 2의 추출 명령이 잘못되었습니다.
세 번째 (Proc) 매개 변수는 앰퍼 샌드로 지정되어 있으며, 즉 루비는 메소드 호출 후 {}-브래킷에있을 것으로 예상합니다.
zipfile.extract(entry, "#{target}/#{entry}"){ true }
또는 (더 복잡한 논리가 필요한 경우)
zipfile.extract(entry, "#{target}/#{entry}") {|entry, path| some_logic(entry, path) }
Post #2에 주어진 예제를 사용하면 "유효하지 않은 인수 (3 for 2)"오류 ...
편집 : 대상 파일이 사전에 존재하는 경우 수정 된 코드.
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
if File.exist?(f_path) then
FileUtils.rm_rf f_path
end
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
편집 : 대상 디렉토리가 사전에 존재하는 경우 수정 된 코드.
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
if File.exist?(destination) then
FileUtils.rm_rf destination
end
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
여기에 있습니다 Mark Needham의 원본 코드:
require 'rubygems'
require 'fileutils'
require 'zip/zip'
def unzip_file(file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
end
unzip_file('/path/to/file.zip', '/unzip/target/dir')
이것 여기 링크 작품을 확인한 좋은 예를 제공합니다. 필요한 'FileUtils'가 추가되면됩니다.