Skip to content

Instantly share code, notes, and snippets.

@MarkoZabcic
Created December 3, 2009 23:32
Show Gist options
  • Save MarkoZabcic/248671 to your computer and use it in GitHub Desktop.
Save MarkoZabcic/248671 to your computer and use it in GitHub Desktop.
#
# Paperclip convert id => id_partition
#
require 'ftools' #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("/")
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
@hubsmoke
Copy link

hubsmoke commented Nov 9, 2011

Just wanted to say that this worked great for me, all I had to do was change require 'ftools' to require 'fileutils' as is hinted in the source code above. The reason for this is because I am using Ruby 1.9. Additionally, I changed line 17 to be simply base_dir=path and when I run it, I just set the full path in that variable. My particular case required a path that looked like photos/data not just photos

Thanks for the excellent work, you sure saved me some time.

@MarkoZabcic
Copy link
Author

Wow.. that was long time ago :-) I'm glad it was of help.

@heaven
Copy link

heaven commented Apr 21, 2012

It was very helpful for me also, thanks.

@ingeniarius
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment