Skip to content

Commit

Permalink
Handle double filenames
Browse files Browse the repository at this point in the history
  • Loading branch information
madeindjs committed Dec 3, 2018
1 parent 9a2ad36 commit 2d710bd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
23 changes: 20 additions & 3 deletions lib/active_storage/send_zip.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
require 'rails'
require 'zip'
require 'tempfile'
require 'pathname'

module ActiveStorage
module SendZip
Expand Down Expand Up @@ -31,15 +32,31 @@ def save_files_on_server(files)
require 'zip'
# get a temporary folder and create it
temp_folder = Dir.mktmpdir 'active_storage-send_zip'
# FileUtils.mkdir_p(temp_folder) unless Dir.exist?(temp_folder)

# count each files to avoid duplicates
filepaths = []

# download all ActiveStorage into
files.map do |picture|
files.each do |picture|
filename = picture.filename.to_s
filepath = File.join temp_folder, filename

# ensure that filename not exists
if filepaths.include? filepath
# create a new random filenames
basename = File.basename filename
extension = File.extname filename

filename = "#{basename}_#{SecureRandom.uuid}#{extension}"
filepath = File.join temp_folder, filename
end

File.open(filepath, 'wb') { |f| f.write(picture.download) }
filepath

filepaths << filepath
end

filepaths
end

# Create a temporary zip file & return the content as bytes
Expand Down
16 changes: 8 additions & 8 deletions test/active_storage/send_zip_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ def test_it_should_save_two_active_support
assert_produce_files files, count: 2
end

# def test_it_should_save_two_active_support
# files = [
# ActiveStorageMock.new('foo.txt'),
# ActiveStorageMock.new('foo.txt')
# ]
#
# assert_produce_files files, count: 2
# end
def test_it_should_save_two_active_support
files = [
ActiveStorageMock.new('foo.txt'),
ActiveStorageMock.new('foo.txt')
]

assert_produce_files files, count: 2
end

private

Expand Down

0 comments on commit 2d710bd

Please sign in to comment.