Created
August 13, 2013 21:51
-
-
Save jessecurry/6226080 to your computer and use it in GitHub Desktop.
Rake task for migrating paperclip attachments stored on S3 when you have to change your path.
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
namespace :paperclip_migration do | |
desc 'Migrate data' | |
task :migrate_s3 => :environment do | |
# Make sure that all of the models have been loaded so any attachments are registered | |
puts 'Loading models...' | |
Dir[Rails.root.join('app', 'models', '**/*')].each { |file| File.basename(file, '.rb').camelize.constantize } | |
# Iterate through all of the registered attachments | |
puts 'Migrating attachments...' | |
attachment_registry.each_definition do |klass, name, options| | |
puts "Migrating #{klass}: #{name}" | |
klass.find_each(batch_size: 100) do |instance| | |
attachment = instance.send(name) | |
unless attachment.blank? | |
attachment.styles.each do |style_name, style| | |
old_path = interpolator.interpolate(old_path_option, attachment, style_name) | |
new_path = interpolator.interpolate(new_path_option, attachment, style_name) | |
# puts "#{style_name}:\n\told: #{old_path}\n\tnew: #{new_path}" | |
s3_copy(s3_bucket, old_path, new_path) | |
end | |
end | |
end | |
end | |
puts 'Completed migration.' | |
end | |
############################################################################# | |
private | |
# Paperclip Configuration | |
def attachment_registry | |
Paperclip::AttachmentRegistry | |
end | |
def s3_bucket | |
ENV['S3_BUCKET'] | |
end | |
def old_path_option | |
':class/:id_partition/:attachment/:hash.:extension' | |
end | |
def new_path_option | |
':class/:attachment/:id_partition/:style/:filename' | |
end | |
def interpolator | |
Paperclip::Interpolations | |
end | |
# S3 | |
def s3 | |
AWS::S3.new(access_key_id: ENV['S3_KEY'], secret_access_key: ENV['S3_SECRET']) | |
end | |
def s3_copy(bucket, source, destination) | |
source_object = s3.buckets[bucket].objects[source] | |
destination_object = source_object.copy_to(destination, {metadata: source_object.metadata.to_h}) | |
destination_object.acl = source_object.acl | |
puts "Copied #{source}" | |
rescue Exception => e | |
puts "*Unable to copy #{source} - #{e.message}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This probably saved a kg of my hair..thx!