Serving assets in Rails 3.1 with nginx
Posted: June 7th, 2011 | Author: jgeiger | Filed under: ruby, web | 3 Comments »I decided to create a site that uses the new Rails 3.1rc. I have a nice setup for nginx to serve my static assets and I was able to get it working with rails 3.1. There’s nothing really too tricky since it’s setup to do it, but you need to make sure that you pre-compile your assets when deploying. The only confusing bit is that you should remove all of your assets before running the rake task to make sure you’re not duplicating files and/or serving the wrong thing. I did a bit of testing and found it was necessary to remove the files and re-compile before starting the server to get the correct files served. I’ve added a small snippet of code below to show how I did it. I also decided it wasn’t necessary to symlink the files into the shared directory since they were getting removed on every deploy anyway. I’m sure there’s a way to only delete the files that changed, but for now this works.
Just a note: it’s good practice to make any line with a ‘cd’ command chainable, so that you’d not accidentally removing a directory in the current working directory if the ‘cd’ command fails:
‘run “cd #{current_path} && rm -rf public/assets/*”‘
Also, ‘current_path’ should be ‘release_path’, because you’ll want to run this before you symlink into production (otherwise a request a couple milliseconds later will trigger Rails to compile assets on it’s own, while you’re also running the rake task).
a.k.a. the hook you’ll want:
before “deploy:symlink”, “assets:precompile_assets”
Depending on your setup, current_path or release_path will work. If you use a git deploy, there is no release path (which btw is why the bundler capistrano tasks fail)
To anyone else who follows a google search here, the correct way with capistrano now is “load deploy/assets”.
The recipes can be found here: https://github.com/capistrano/capistrano/blob/master/lib/capistrano/recipes/deploy/assets.rb