Skip to content

Instantly share code, notes, and snippets.

@ingeniarius
Forked from MarkoZabcic/paperclip_extend.rake
Created July 30, 2012 12:18
Show Gist options
  • Save ingeniarius/3206511 to your computer and use it in GitHub Desktop.
Save ingeniarius/3206511 to your computer and use it in GitHub Desktop.
#
# Paperclip convert id => id_partition
#
require 'fileutils'
class PaperclipExtend
def self.obtain_class
class_name = ENV['CLASS'] || ENV['class']
uploads_path = ENV['UPLOADS_PATH'] || ENV['uploads_path']
raise "Must specify CLASS" unless class_name
raise "Must specify UPLOADS_PATH" unless uploads_path
[class_name.tableize, uploads_path]
end
def self.convert_id_to_id_partition
klass, path = obtain_class
#base_dir = [path, klass].join("/")
base_dir = path
dirs = Dir.entries(base_dir)
dirs.each do |dir|
id = dir
if id.to_i == 0
# example . | .. | 000
puts "Not a valid directory #{id}"
else
id_partition = paperclip_id_partition(id.to_i)
old_path = [base_dir, id].join("/")
new_path = [base_dir, id_partition].join("/")
FileUtils.mkdir_p(new_path)
FileUtils.mv Dir.glob("#{old_path}/*"), new_path, :verbose => false
FileUtils.rmdir old_path
puts "#{old_path.ljust(base_dir.length+5)} => #{new_path}"
end
end
end
def self.paperclip_id_partition(id)
("%09d" % id).scan(/\d{3}/).join("/")
end
end
namespace :paperclip do
desc "Convert id => id_partition for given CLASS and UPLOADS_PATH e.g. 'public/uploads'"
task :id_to_id_partition => :environment do
PaperclipExtend.convert_id_to_id_partition
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment