Last active
February 13, 2017 19:59
-
-
Save ksin/7747334d60b1947f14e9 to your computer and use it in GitHub Desktop.
Paperclip copy attachments s3
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. | |
### Refer to Paperclip issue: https://github.com/thoughtbot/paperclip/issues/1361#issuecomment-39684643 | |
### Original gist works with fog: https://gist.github.com/stereoscott/10011887 | |
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 Excon::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_coordinator.bucket attachment.bucket_name | |
end | |
def s3_coordinator | |
@s3_coordinator ||= S3Coordinator.new | |
end | |
def copy_object(source_bucket, source_path, destination_bucket, destination_path) | |
s3_coordinator.copy(from_bucket: source_bucket, | |
from_path: source_path, | |
to_bucket: destination_bucket, | |
to_path: destination_path, | |
options: {acl: :public_read}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, where do you get the S3Coordinator class from? Thank you.