Asset Pipeline with Heroku

Rails 3’s asset pipeline is a great way to organise javascript, css and images. One app I’m working on at the moment deploys to Heroku and doing the asset precompile on Heroku could be slow. When deploying to Heroku, the time spent on doing asset precompile is unnecessary and unbearable, especially if the new changes have nothing to do with assets …

The best solution I can find is http://icelab.com.au/articles/asset-pipeline-tips/. However it’s quite high level, so here’s a step by step instruction on how I accomplished the task.

First, add the asset_sync gem to your Gemfile inside the assets group, and bundle install it

gem "asset_sync"

Go to /config/application.rb, append any custom js and/or css files to the precompile list

config.assets.precompile += %w(corporate.css corporate.js reset.css)

Edit /config/environments/production.rb to add the asset_host option

config.action_controller.asset_host = "http://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"

Run the following to generate the asset_sync initialis(z)er. Tweak the config as your wish.

rails g asset_sync:install --provider=AWS

Next up, add all necessary AWS credentials as ENV vars

export FOG_DIRECTORY=xxxxxxxx
export AWS_ACCESS_KEY_ID=xxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxx

One thing to notice is the FOG_DIRECTORY value. It is the bucket name you created on S3. I was using _ in the bucket name, asset_sync or fog to be specific was complaining about the name. Updating the bucket names to use . instead of _ muted all the noises.

I also configured the above 3 ENV vars on Heroku, but I think only FOG_DIRECTORY is required.

Now, precompiling assets locally by doing

bundle exec rake assets:precompile

The above will put all the compiled assets in /public/assets. Now we need to make git happy.

First, stage and commit /public/assets/manifest.yml. Then edit .gitignore by adding

#Ignore compiled assets except the manifest
public/assets/
!public/assets/manifest.yml

This will make git track the asset manifest, but ignore all the other compiled asset files (coz they are already uploaded to S3 as a post asset compilation step by asset_sync).

All good, all working… But wait a second … Now when developing locally, compiled assets from /public/assets are all loaded … trouble !!!

At the moment, I’m doing what’s suggested

bundle exec rake assets:clean && git checkout public/assets/manifest.yml

That’s all.

Published: 2012-07-11
blog comments powered by Disqus