Skip to content

Instantly share code, notes, and snippets.

@cajun-code
Forked from serek/migration.rb
Created May 18, 2011 18:28
Show Gist options
  • Save cajun-code/979182 to your computer and use it in GitHub Desktop.
Save cajun-code/979182 to your computer and use it in GitHub Desktop.
Migration from attachment_fu to paperclip.
class ConvertImagesToPaperclip < ActiveRecord::Migration
include PaperclipMigrations
def self.up
# Paperclip
add_column :images, :data_file_name, :string
add_column :images, :data_content_type, :string
add_column :images, :data_file_size, :integer
add_column :images, :data_updated_at, :datetime
# Update table information
Image.reset_column_information
# Delete all attachement_fu image sizes
Image.delete_all("parent_id IS NOT NULL")
remove_column :images, :parent_id
# Migrate data
Image.all.each do |image|
populate_paperclip_from_attachment_fu(image, image, 'data', 'userimages') if image
image.reprocess! if image
end
# After data migration and paperclip reprocessing remove attachement_fu columns
remove_column :images, :filename
remove_column :images, :content_type
remove_column :images, :size
end
def self.down
raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted data (Image)."
end
end
module PaperclipMigrations
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def populate_paperclip_from_attachment_fu(model, attachment, prefix, path_prefix)
unless attachment.filename.nil?
model.send("#{prefix}_file_name=", attachment.filename)
model.send("#{prefix}_content_type=", attachment.content_type)
model.send("#{prefix}_file_size=", attachment.size)
puts "# data_file_name: #{model.send("#{prefix}_file_name")}"
puts "# data_content_type: #{model.send("#{prefix}_content_type")}"
puts "# data_file_size: #{model.send("#{prefix}_file_size")}"
# Get file path from attachment_fu
file_path = ("%08d" % model.id).scan(/..../).join('/')
old_path = File.join(RAILS_ROOT, 'public', path_prefix, file_path, attachment.filename)
new_path = model.send(prefix).path(:original)
new_folder = File.dirname(new_path)
if File.exists?(old_path)
unless File.exists?(new_folder)
FileUtils.mkdir_p(new_folder)
end
puts "Copying #{old_path} to #{new_path}"
system("cp #{old_path} #{new_path}")
model.save
else
puts "No such file: #{old_path}"
end
puts "# -------- END #"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment