Read more

Paperclip: Move attachements from local storage to AWS S3

Thomas Eisenbarth
September 10, 2012Software engineer at makandra GmbH

We frequently use the handy Paperclip Gem Show archive.org snapshot to manage file attachments.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

If you need to move the files from local storage (i.e., your servers' harddisk) to Amazon S3, you can simply change settings for Paperclip to use the S3 storage adapter and use this script to migrate to S3. Put the snippet into a chore if you don't want to run that in the console.
YOUR_LOCAL_STORAGE_MODEL_DIRECTORY should be something like 'storage/your_model'.

Dir.glob(YOUR_LOCAL_STORAGE_MODEL_DIRECTORY**/*).each do |path|
  attachment = File.open path

  # skip directories
  next if File.directory? attachment

  full_path = File.expand_path attachment
  # find id to update
  id = full_path.match(/(\d+)\/original\/.+$/)[1]

  puts "Re-saving ##{id}..."
  your_model = YOURMODEL.find(id)
  
  # Paperclip will re-save the attachment using the new settings
  your_model.document = attachment
  your_model.save

end
Posted by Thomas Eisenbarth to makandra dev (2012-09-10 18:07)