Basically, we came up with this task at work. I was wondering if there's a shorter and cleaner way of doing the following in some other language (or even improving what I did with Ruby).
We have a folder. In this folder we have files (images only, /w .jpg
extension). The names of the images are random strings such as:
- 3e3eaa0b927d0158e1b2479ce31000b3.jpg
- 3e3eaa0b927d0158e1b2479ce31000b3_1.jpg
- 99a2b9c3442e716fc486e46abcfcfb05.jpg
- 99a2b9c3442e716fc486e46abcfcfb05_1.jpg
- 99a2b9c3442e716fc486e46abcfcfb05_2.jpg & etc.
To make it clearer, those images were related to certain objects. An object had multiple images (not a specific amount). We have to get those images, read their name, and get the "unique" part.
Example: For images:
- 3e3eaa0b927d0158e1b2479ce31000b3.jpg
- 3e3eaa0b927d0158e1b2479ce31000b3_1.jpg
the "unique" part is "3e3eaa0b927d0158e1b2479ce31000b3"
And we have to create a folder with this name (3e3eaa0b927d0158e1b2479ce31000b3) and put all the images that match (3e3eaa0b927d0158e1b2479ce31000b3_*). Also we have to rename those images, so in every folder there must be one image with thumb_
followed by a random string & the other images must be with img_
prefix and again followed by a random string.
This is my try:
require 'securerandom'
folder = "storage_test/"
Dir.glob("#{folder}*.jpg") do |img|
fn = File.basename(img,".*").gsub(/(\_\d)+/, '') #folder name
prefix = (!File.exists?( "#{folder}#{fn}") ? '/thumb_' : '/img_') #prefix
new_name = "#{folder}#{fn}/#{prefix}" + SecureRandom.hex(32) + File.extname(img) #new_name (of the image)
Dir.mkdir("#{folder}#{fn}") unless File.exists?("#{folder}#{fn}") #create the folder
File.rename(img, new_name) #move
end
(I work on Windows)
I'm sorry I've probably misused the term random
. By random I mean that I need to create a name that's unique
to the certain folder. Actually, there aren't going to be more than 40-50 files in a folder, so I presumed that SecureRandom.hex(32)
will generate unique
enough filename that will not cause overwriting in the same folder.
More detailed example:
Example folder: "storage_test"
And this is a part of its content:
I've grouped the files that should go in the same folder. I highlighted that part from the file's name that should be used as folders name.
So after executing the code "storage_test"
will have:
- 091afecdc49a8e8e581f11f2f1bfea8f_1/thumb_unique(to the folder)name.jpg
- 091afecdc49a8e8e581f11f2f1bfea8f_1/img_unique(to the folder)name.jpg
- 091afecdc49a8e8e581f11f2f1bfea8f_1/img_unique(to the folder)name.jpg