The version below is specifically tailored to handle a model named Item
where the attachment is called image
.
#!/usr/bin/env ruby
require "fileutils"
if File.directory? "public/system/items/images"
puts "Nothing to do, you've already done this"
exit 0
end
# Create the new folder
FileUtils.mkdir_p "public/system/items/images"
# This will store an array of Folder instances
folders = nil
Folder = Struct.new(
:id, # Current folder name 1234567
:id_partition, # New folder name 001/234/567
:parent_partition # Parent folder name 001/234
)
# Find all old folders map into Folder instances
FileUtils.cd "public/system/images" do
folders = Dir["*"].sort_by(&:to_i).map do |folder_name|
id = folder_name.to_i
arr = format("%09d", id).scan(/\d{3}/)
id_partition = arr.join("/")
parent_partition = arr.take(2).join("/")
Folder.new(id, id_partition, parent_partition)
end
end
# Prepare by creating parent folders ***/***
folders.collect(&:parent_partition).uniq.sort.each do |parent_partition|
path = "public/system/items/images/#{parent_partition}"
FileUtils.mkdir_p path
puts "Creating folder #{path}"
end
# Then rename folders into the new id_partition structure
folders.each do |folder|
from = "public/system/images/#{folder.id}"
to = "public/system/items/images/#{folder.id_partition}"
puts "MOVING #{"%-30s" % [from]} INTO #{to}"
FileUtils.mv from, to
end
FileUtils.rmdir "public/system/images"
puts "DONE"