Skip to content

Instantly share code, notes, and snippets.

@scmx
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scmx/cf471c13333712c789d9 to your computer and use it in GitHub Desktop.
Save scmx/cf471c13333712c789d9 to your computer and use it in GitHub Desktop.
Migrate old paperclip folders into the newer id_partition structure #rails #paperclip #id_partition #migrate

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment