Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfgomez86/1953084 to your computer and use it in GitHub Desktop.
Save jfgomez86/1953084 to your computer and use it in GitHub Desktop.
Rails 3.1: Precompile Assets for Cloudfront/CDN support

Naming files and using asset_path

application.scss.erb
- use <%= asset_path 'background.jpg' %>

on config/environments/production.rb

config.assets.precompile = %w(application.js books.js  html5.js ie7.css book_functions.js *.css)

This will precompile selected files only

config.assets.precompile += %w(*.gif *.js  *.png *.jpg *.css.erb *.css)
config.assets.precompile = [/^[^_]/] #precompile everything except partials

This will precompile files based on extension including images. Rails 3.1 by default doesn’t precompile all javascripts or stylesheets. It only precompiles application.css for example. So if you have admin.css, that isn’t precompiled.

Notes

Rails 3.1 is the most sensible version of Rails so far. It supports CDN well.

On production.rb

config.action_controller.asset_host = "http://youruniqueid.cloudfront.net"

But even before you do that, make sure you have precompiled assets, uploaded them and gave proper permissions.

My capistrano tasks:

config/deploy/production.rb


before "deploy:symlink", "deploy:assets"

desc "Compile asets"
task :assets do
  rails_env = fetch(:rails_env, 'production')
  run "cd #{release_path}; RAILS_ENV=#{rails_env} bundle exec rake assets:precompile"
end

Nginx Config

This was posted by Cyril David (@cyx):

listen 80;
server_name subdomain.yourdomain.com;
rewrite "^/([0-9]+)/(.*)" /$2;

expires max;

root /srv/sitename.com/public;
}

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