Skip to content

Instantly share code, notes, and snippets.

@stereoscott
Created April 6, 2014 21:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stereoscott/10011887 to your computer and use it in GitHub Desktop.
Save stereoscott/10011887 to your computer and use it in GitHub Desktop.
Paperclip Copy Attachments
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)
connection = destination_attachment.send(:connection)
source_bucket ||= source_attachment.options[:fog_directory]
destination_bucket ||= destination_attachment.options[:fog_directory]
[:original, *destination_attachment.styles.keys].uniq.map do |style|
source_path = source_attachment.path(style)
destination_path = destination_attachment.path(style)
options = {}
options['x-amz-acl'] = 'public-read' if destination_attachment.fog_public(style)
Paperclip.log("Copying #{style} from #{source_bucket}/#{source_path} ---> #{destination_bucket}/#{destination_path}")
begin
connection.copy_object(source_bucket, source_path, destination_bucket, destination_path, options)
rescue Excon::Errors::NotFound
Paperclip.log("Could not find #{style} from #{source_bucket}/#{source_path}")
end
end
end
end
end
end
@johnnyshields
Copy link

If you are using different :fog only in certain environments, change line 6 to:

        next unless source_attachment.present? && source_attachment.options[:storage] == :fog

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