Abusing Rails' Middleware to Rewrite Paperclip S3 URLs

December 03, 2014

One of the sites I’m working on has a lot of S3 assets stored using Paperclip. The site has different buckets for production and staging. In development, S3 isn’t used at all, just local files. For this site we backup the production database and make it available in both staging and development environments. It just makes life easier.

Except all of the images are broken.

This middleware fixes that by replacing staging sources with production sources.

In staging all that is necessary is to replace the S3 bucket name.

In development we tweak things slightly so that if a local version exists we’ll use that, otherwise we replace things so that the production S3 URl is used.

To install this on your own site, grab the middleware, and save it in lib/amazon_s3_munger.rb, then add the following line to config/environments/development.rb and config/environments/staging.rb:

config.middleware.use 'AmazonS3Munger'

You will most certainly need to tweak the code to match your own needs.

Before –––––> After