Paperclip: Move attachements from local storage to AWS S3

Updated . Posted . Visible to the public.

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

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
Thomas Eisenbarth
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Eisenbarth to makandra dev (2012-09-10 16:07)