Skip to content

Instantly share code, notes, and snippets.

@ksin
Last active February 13, 2017 19:59
Show Gist options
  • Save ksin/7747334d60b1947f14e9 to your computer and use it in GitHub Desktop.
Save ksin/7747334d60b1947f14e9 to your computer and use it in GitHub Desktop.
Paperclip copy attachments s3
### 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
@martincik
Copy link

Hey, where do you get the S3Coordinator class from? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment