Skip to content

Instantly share code, notes, and snippets.

@wader
Created October 19, 2011 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wader/1299311 to your computer and use it in GitHub Desktop.
Save wader/1299311 to your computer and use it in GitHub Desktop.
Paperclip change path migration helper
# WARNING: don't just use this without testing!
# This is not a database migration but i think it's quite convenient to do as a migration
# multiple styles has not been tested but should work
class ChangeAttachmentPaths < ActiveRecord::Migration
AttachmentPath = Rails.root.join("public", "system")
def self.paperclip_change_path(table, column, old_opt, new_opt)
model = table.to_s.classify.constantize
# build {[id, style] => [old_path, new_path], ...}
rename_map = {}
model.has_attached_file column, old_opt
model.all.each do |r|
c = r.send(column)
next if not c.file?
styles = c.styles.keys
styles = [:original] if styles.empty?
styles.each do |style|
rename_map[[r.id, style]] = [c.path(style)]
end
end
model.has_attached_file column, new_opt
model.all.each do |r|
c = r.send(column)
styles = c.styles.keys
styles = [:original] if styles.empty?
styles.each do |style|
next if not rename_map.has_key? [r.id, style]
rename_map[[r.id, style]].push(c.path(style))
end
end
# rename files
rename_map.values.each do |old_path, new_path|
#puts "FileUtils.mkdir_p #{File.dirname(new_path)}"
#puts "File.rename #{old_path}, #{new_path}"
FileUtils.mkdir_p File.dirname(new_path)
File.rename old_path, new_path
end
# remove empty directories
Dir[AttachmentPath.join(table.to_s, column.to_s.pluralize, "**/*")]
.select { |d| File.directory? d }
.select { |d| (Dir.entries(d) - %w[ . .. ]).empty? }
.each { |d| Dir.rmdir d }
end
def self.up
paperclip_change_path :users, :profile_image,
{:path => ":rails_root/public:url", :url => "/system/:class/:attachment/:id/:style.:extension"},
{:path => ":rails_root/public:url", :url => "/system/:class/:attachment/:id/:filename"}
end
def self.down
paperclip_change_path :users, :profile_image,
{:path => ":rails_root/public:url", :url => "/system/:class/:attachment/:id/:filename"},
{:path => ":rails_root/public:url", :url => "/system/:class/:attachment/:id/:style.:extension"}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment