Skip to content

Instantly share code, notes, and snippets.

@airblade
Created November 10, 2015 11:01
Show Gist options
  • Save airblade/a6c9ea0f6888d4ce1bcd to your computer and use it in GitHub Desktop.
Save airblade/a6c9ea0f6888d4ce1bcd to your computer and use it in GitHub Desktop.
Copies S3-stored Paperclip attachments from one AR model to another
# lib/paperclip/copy_attachments.rb
# Copies S3-stored Paperclip attachments from one AR model to another.
#
# This module should be mixed into the target AR model.
if Gem::Version.new(::AWS::VERSION) >= Gem::Version.new(2)
raise NotImplementedError, 'coded for aws-sdk v1'
end
module Paperclip
module CopyAttachments
# Copies S3-stored attachments from the source ActiveRecord instance.
def copy_attachments_from(source)
self.class.attachment_definitions.keys.each do |attachment_name|
source_attachment = source.send attachment_name
next if source_attachment.blank?
next if source_attachment.options[:storage] != :s3
destination_attachment = send attachment_name
[:original, *destination_attachment.styles.keys].uniq.map do |style|
Paperclip.log "S3 copy: #{source_attachment.path(style)} -> #{destination_attachment.path(style)}"
source_s3_object = source_attachment.s3_object style
destination_s3_object = destination_attachment.s3_object style
source_s3_object.copy_to destination_s3_object, acl: source_attachment.s3_permissions(style)
end
end
end
end
end
# config/initializers/paperclip.rb
require 'paperclip/copy_attachments'
ActiveRecord::Base.send :include, Paperclip::CopyAttachments
@PaulRHanson316
Copy link

Hello @airblade,

This is such a great implementation! I'm using Rails 5 with aws-sdk gem v 2.3.0. Is there a solution for that version?

Thanks!

@marlonmantilla
Copy link

Thanks! this worked like a charm!!

For people implementing this, the duplicated record must be saved before calling copy_attachments_from.

@tiagogeraldi
Copy link

working with gem 'aws-sdk-s3' '1.30' but I had to remove the gem version checker of the top.

Thanks a lot.

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