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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)