Skip to content

Instantly share code, notes, and snippets.

@fleveque
Last active November 2, 2015 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fleveque/e1271f6063ca283fe86a to your computer and use it in GitHub Desktop.
Save fleveque/e1271f6063ca283fe86a to your computer and use it in GitHub Desktop.
rake task to migrate paperclip attachments to Amazon S3 using aws-sdk v1
namespace :attachments do
task migrate_to_s3: :environment do
require 'aws-sdk'
# Define Paperclip models (change with your own)
models = [
[Model1, :data],
[Model2, :logo]
]
# Load credentials and config
s3_options = YAML.load_file(File.join(Rails.root, 'config/aws.yml'))[Rails.env].symbolize_keys
paperclip_options = YAML.load_file(File.join(Rails.root, 'config/paperclip.yml'))[Rails.env].symbolize_keys
bucket_name = paperclip_options[:bucket]
# Establish S3 connection
AWS.config(s3_options)
s3 = AWS::S3.new
bucket = s3.buckets[bucket_name]
models.each do |klass, field|
styles = []
# Collect all the styles, all are uploaded because `rake paperclip:refresh CLASS=Attachment` is broken for mongoid
klass.first.send(field).styles.each do |style|
styles.push(style[0])
end
styles.push(:original)
# Process
klass.all.each_with_index do |attachment, n|
styles.each do |style|
path = attachment.send(field).path(style)
next if path.nil?
begin
bucket.objects[path].write(file: File.join(Rails.public_path, path))
puts "-> Saved #{path} to S3 (#{n}/#{klass.count})"
rescue AWS::S3::Errors::NoSuchBucket => e
puts "--- Creating bucket named: #{bucket_name} ---"
AWS::S3.new.buckets.create(bucket_name)
retry
rescue StandardError => e
puts "Error on (#{n}/#{klass.count}): #{e}"
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment