2017-04-05 59 views
1

使用例如下面的測試樹文件夾添加一個同名文件:Rubyzip無法從另一個文件夾[郵編:: EntryExistsError]

- test1 
- folder2 
    - test1 # This is the file rubyzip will break on. 
    - test2 

並複製該代碼here

path = File.expand_path path 
archive = File.join(__dir__, File.basename(path)) + '.zip' 
FileUtils.rm archive, force: true 

Zip::File.open(archive, Zip::File::CREATE) do | zipfile | 
    Dir["#{path}/**/**"].reject{|f|f==archive}.each do | item | 
    basename = File.basename(item) 
    zipfile.add(basename, item) 
    end 
end 

它失敗了,因爲有兩個文件具有相同的名稱,即使它們不在同一個目錄中(本例中爲test1)。

有什麼我失蹤?

+0

如果這不是正確的行爲,我應該將問題發佈到gem'rubyzip'嗎? – Hellfar

回答

0

感謝@simonoff(here),我不應該使用基本名稱,而是完整的相對路徑,以便Rubyzip可以區分test1folder2/test1

這裏是修復它代碼:

basename = File.basename path 
dirname = File.dirname path 
internal_path = path.sub %r[^#{__dir__}/], '' 

archive = File.join(dirname, basename) + '.zip' 
FileUtils.rm archive, force: true 

Zip::File.open(archive, Zip::File::CREATE) do | zipfile | 
    Dir["#{internal_path}/**/**"].map{|e|e.sub %r[^#{internal_path}/],''}.reject{|f|f==archive}.each do | item | 
    zipfile.add(item, File.join(internal_path, item)) 
    end 
end 

當然是有一個更清潔的方式來做到這一點。

相關問題