Created
August 25, 2015 12:24
-
-
Save builtinnya/24c2ca12969fc79a0d69 to your computer and use it in GitHub Desktop.
Paperclip S3 copy attachments
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
### S3 implementation of Paperclip module that supports deep | |
### cloning of objects by copying image attachments. | |
### | |
### Tested with: aws-sdk (1.33.0) | |
### | |
### Refer to Paperclip issue: https://github.com/thoughtbot/paperclip/issues/1361#issuecomment-39684643 | |
### Original gist works with fog: https://gist.github.com/stereoscott/10011887 | |
### gist works from which this code is derived: https://gist.github.com/ksin/7747334d60b1947f14e9 | |
module Paperclip | |
module CopyAttachments | |
def copy_attachments_from(source_obj, source_bucket = nil, destination_bucket = nil) | |
self.class.attachment_definitions.keys.each do |attachment_name| | |
source_attachment = source_obj.send(attachment_name) | |
next if source_attachment.blank? | |
destination_attachment = self.send(attachment_name) | |
source_bucket ||= bucket source_attachment | |
destination_bucket ||= bucket destination_attachment | |
[:original, *destination_attachment.styles.keys].uniq.map do |style| | |
source_path = path(source_attachment, style) | |
destination_path = path(destination_attachment, style) | |
Paperclip.log("Copying #{style} from #{source_bucket}/#{source_path} ---> #{destination_bucket}/#{destination_path}") | |
begin | |
copy_object(source_bucket, source_path, destination_bucket, destination_path) | |
rescue AWS::S3::Errors::NotFound | |
Paperclip.log("Could not find #{style} from #{source_bucket}/#{source_path}") | |
end | |
end | |
end | |
end | |
private | |
def path(attachment, style) | |
path = attachment.path(style) | |
path.slice!(0) if path.start_with? '/' | |
path | |
end | |
def bucket(attachment) | |
s3.buckets[attachment.bucket_name] | |
end | |
def s3 | |
return @s3 if @s3 | |
# Load credentials from a file. | |
# Change this line (and key names below) to match your environment. | |
creds = YAML.load(File.read("#{ Rails.root }/config/s3.yml")) | |
@s3 = AWS::S3.new( | |
access_key_id: creds['access_key_id'], | |
secret_access_key: creds['secret_access_key'], | |
s3_endpoint: 'YOUR_S3_ENDPOINT' | |
) | |
end | |
def copy_object(source_bucket, source_path, destination_bucket, destination_path) | |
source_obj = source_bucket.objects[source_path] | |
destination_obj = destination_bucket.objects[destination_path] | |
source_obj.copy_to(destination_obj, acl: :public_read) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@builtinnya What version of Paperclip does this work with?