In testing my Photo Organizing Script, I noticed something scary.
If I move an image into a folder where another DIFFERENT image has the SAME name, the move function overwrites previous image.
No warning.
This is a pretty serious issue, since it will result in data loss.
It’s time to write a function to detect for this and rename the file.
def move_safely (file, folderName)
if File.exists?(folderName+"/"+file)
puts "the file exists and should not be overwritten!"
#rename the file
#generate an 8 char random string to append to the file name.
random8 = (0...8).map{(65+rand(26)).chr}.join
#break up the file into file and file type. The result of this is an array
breakUp = file.split(".")
#add the fixin's to the random8 string
randomize = "_"+random8+"."
#insert it into the array
breakUp.insert(1,randomize)
#convert the array into a file string
newFileName = breakUp.join
File.rename(file,newFileName)
file = newFileName
else
puts "the file doesn't exist"
end
FileUtils.move file, folderName
end