Skip to content

Instantly share code, notes, and snippets.

@jasoares
Forked from michiels/paperclip_migration.rake
Last active December 24, 2015 20:19
Show Gist options
  • Save jasoares/6857021 to your computer and use it in GitHub Desktop.
Save jasoares/6857021 to your computer and use it in GitHub Desktop.
# migrate all images to S3
namespace :paperclip_migration do
desc "migrate files from filesystem to s3"
task :migrate_to_s3 => :environment do
local_filesystem_root = Rails.root.to_s + "/public/system"
# Fetch all models and find out which ones have paperclip attachments
Rails.application.eager_load!
models = ActiveRecord::Base.send(:descendants).select {|model| model.respond_to?(:attachment_definitions) }
models.each do |model|
definitions = model.attachment_definitions
attachment_types = model.attachment_definitions.keys
model.find_each do |record|
attachment_types.each do |attachment_type|
attachment = Paperclip::Attachment.new(attachment_type, record, definitions[attachment_type].except(:s3_credentials, :storage))
next if attachment.path.nil? # skip if this record has no image
if File.exists?(local_filesystem_root + attachment.path)
file_data = File.open(local_filesystem_root + attachment.path)
puts "Storing file: #{local_filesystem_root + attachment.path} on Amazon S3..."
record.send("#{attachment_type}=", file_data)
record.send("#{attachment_type}").save
else
puts "Could not find: #{local_filesystem_root + attachment.path}. Skipping..."
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment