Skip to content

Instantly share code, notes, and snippets.

@audionerd
Last active September 1, 2015 17:24
Show Gist options
  • Save audionerd/a21cf119256af4f59492 to your computer and use it in GitHub Desktop.
Save audionerd/a21cf119256af4f59492 to your computer and use it in GitHub Desktop.
Configure Rails to serve image files via Imgix

Configure Rails to serve image files via Imgix

Once you have Imgix setup to pull in images from your server, you'll want to tell Rails which assets to serve via Imgix and which to serve directly.

Something like the following in config/environments/production.rb will help:

config.action_controller.asset_host = Proc.new { |source|
  if source.ends_with?('.jpg') || source.ends_with?('.gif') || source.ends_with?('.png')
    # the image host
    # for jpg, gif, png
    "example.imgix.com"
  else
    # the asset host
    # for js, css, svg, etc.
    "example.com"
  end
}

Note that we're just doing source.ends_with? which is simple to understand, but it won't catch everything (uppercase filenames for example won't be caught). See the StackOverflow post referenced below for a RegExp based solution.

You can also use a set of environment variables like ENV['IMAGE_HOST'] and ENV['ASSET_HOST'] instead of hardcoding strings to make it easier to adjust these settings on platforms like Heroku.

For image uploads, check out imgix-paperclip

For dynamic resizing based on context, check out imgix.js

For further reference:

@kellysutton
Copy link

Thanks for putting this together! A few things: we no longer recommend using imgix-paperclip. Instead, just use normal paperclip and then use the new imgix-rails gem for Rails-level integration.

If you need something more than view helpers, check out imgix-rb.

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