-
-
Save jasonmclaren/3026560 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# First configure your models to use Amazon s3 as storage option and setup the associated S3 config. | |
# Then add the classes your want to migrate in the klasses array below. | |
# Then run rake paperclip_migration:migrate_to_s3 | |
# Should work but this is untested and may need some tweaking - but it did the job for me. | |
namespace :paperclip_migration do | |
desc "migrate files from filesystem to s3" | |
task :migrate_to_s3 => :environment do | |
# Replace with your real model names. If anyone wants to this could be picked up from args or from configuration. | |
klasses = [:account, :product, :product_category, :studio] | |
klasses.each do |klass_key| | |
puts "moving #{klass_key.to_s}" | |
klass = real_klass(klass_key) | |
next if !klass | |
if !klass.respond_to?(:attachment_definitions) | |
puts "There are no paperclip attachments defined for the class #{klass.to_s}" | |
next | |
end | |
definitions = klass.attachment_definitions | |
puts "with attachments #{definitions.keys.inspect}" | |
klass.find_each(:batch_size => 100) do |record| | |
definitions.keys.each do |definition| | |
next if !record.send("#{definition}_file_name") # don't run if there's no file to upload | |
next if record.send("#{definition}").exists? # don't run if you already uploaded | |
attachment = Paperclip::Attachment.new(definition.to_sym, record, definitions[definition.to_sym].except(:s3_credentials, :storage)) | |
# This is where I grab the existent file url. | |
attachment_url = attachment.url(attachment.default_style, false) | |
attachment_path = Rails.root.to_s + "/public" + attachment_url | |
if !File.exists?(attachment_path) | |
puts "For #{klass_key.to_s} id=#{record.id}, can't find file: #{attachment_path} NOT MIGRATING..." | |
next | |
end | |
file_data = File.open(attachment_path) | |
puts "Saving file: #{attachment_url} to Amazon S3..." | |
record.send("#{definition}").assign file_data | |
record.send("#{definition}").save | |
end | |
end | |
end | |
end | |
def real_klass(key) | |
key.to_s.classify.constantize | |
rescue | |
puts "#{klass_key.to_s.classify} is not defined in this app." | |
nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I added a check so that it skips attachments that have already been uploaded. That way you can run it multiple times, in case you get interrupted. Also did some cosmetic refactoring.