Make Capistrano compress your JavaScript and CSS automatically

I finally gave Capistrano a whirl this morning by setting up a dummy application and getting a deployment to work. I must say, once it’s up and running it makes updating your application about as easy as it conceivably could be, and must save you loads of time if you have your app installed on multiple machines.

Thing is, when pushing code out to the server, I need to make sure my JavaScript and CSS is nicely packed up so I can serve gzipped files to supported browsers. The first step is having AssetPackager build its packages, and the second is finding all the .js and .css files in my app and making compressed copies. This can all be done automatically by adding the following lines to your :after_update_code task in deploy.rb (line wraps marked \:

task :after_update_code, :roles => [:app, :db, :web] do
  # ...
  run "cd #{release_path} && rake asset:packager:build_all"
  run "for file in $(find #{release_path}/public/javascripts \\
      -name '*.js'); do gzip $file -f -c > $file.gz; done"
  run "for file in $(find #{release_path}/public/stylesheets \\
      -name '*.css'); do gzip $file -f -c > $file.gz; done"

All this does is invoke the AssetPackager build task, then it goes into your JS and CSS directories in turn and finds all the JS and CSS files. It loops through the files it finds and makes gzipped copies with ‘.gz’ appended to the filename – the orignial files are left intact so you can serve them to browsers that don’t support gzipped content.

If you've enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It's full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.