Rails 3 Asset Pipeline in a minute
Here's a quick summary of Rails 3's asset pipeline if you're already confident with Rails/Ruby, and some pointers on getting it working on Heroku.
- Rails 3 supports compiling Coffeescript, SASS etc to JS and CSS.
- Rails 3 puts assets in three places, here's a glob:
{app,lib,vendor}/assets/{stylesheets,javascripts}/*.*
- Meta language filetypes go on the end of the target language, like erb, so
jquery.js.coffee
.
Those folders are for:
- app - app specific code
- lib - libraries you've written (shared between apps)
- vendor - other people's code (jQuery, Backbone, etc)
Requiring files in CSS/JS
Requiring them in doesn't require the app
, lib
or vendor
prefix. You don't need a file type suffix. You use Sprocket's //= require asset_name
to pull in other files in JS or CSS (or any language that compiles to either of those).
Grab the sass-rails gem for sass, and compass-rails to avoid reinventing a heap of CSS3/browser compatibility mixins.
Configuration
If you have any top level files (eg that will be in a script
or link
tag) aside from application.{js,css}, they will not be precompiled unless you tell Rails about them manually.
# again, no need to mention .coffee
config.assets.precompile += %w{app.js app.css}
Using it with Heroku
If you're using Heroku with the asset pipleine, you need to turn off initialize on precompilation (they don't set ENV vars, and therefore your initializers will crash). In config/application.rb
, set:
config.assets.initialize_on_precompile = false
Debug precompiltation with the below command Heroku will use. Ideally turn off initialization as above, and if that's not possible, ensure no initialisers hit DBs etc.
env RAILS_ENV=production DATABASE_URL={{YOUR_SCHEME_HERE - prob postgres}}://user:pass@127.0.0.1/dbname bundle exec rake assets:precompile 2>&1
If you've any other gotchas, or if anything is out of date, please let me know!