我已经修改了我的代码,以防止在压缩具有相同文件名的文件时出错。我想更改它,以便增加重复的文件名。
例如,如果您有三个名为file.txt的文件,那么我希望它们是file.txt
,file_2.txt
和file_3.txt
def zip(file_name)
files_added = []
ZipRuby::Archive.open(file_name, ZipRuby::CREATE) do |archive|
file_associations.sort_by { |fa| fa.created_at }.each do |fa|
attachment_file_name = fa.attachment_file_name
binding.pry
if files_added.include?(attachment_file_name)
n = 2
ext = File.extname(attachment_file_name)
base = File.basename(attachment_file_name, ext)
new_name = "#{base}_#{n}#{ext}"
while files_added.include? new_name
n += 1
new_name = "#{base}_#{n}#{ext}"
end
attachment_file_name = new_name
end
archive.add_buffer(attachment_file_name, fa.attachment.read)
files_added << attachment_file_name
end
end
end
上面的代码可以工作,但我是Ruby / Rails的新手,并且感觉不太Rubyist。任何人都可以为重构提供任何指示。