Using YUICompressor with Capistrano and Rails 2.3+ on Combined Javascript and CSS
YUICompressor is a standalone Javascript and CSS minifier from the YUI folks. It’s fairly awesome in that it does deep analysis of Javascript using Rhino (a standalone Javascript interpreter). Most minifiers take the low road and merely remove spaces and newlines, and, if you’re lucky maybe shorten the variable names. YUICompressor one-ups them all because it actually parses all your JS and aggressively optimizes it for download speed.
CSS and Javascript Conflation
The problem is most of the guides out there for integrating YUICompressor with Capistrano and Rails are woefully out-of-date. The main issue is that Rails now has built-in support for combining all JS files into a single file. So, there’s no need to manually do this in Capistrano these days.
You can make Rails combine automatically combine your Javascript by adding a :cache => "cache/all" to your javascript_include_tag and stylesheet_link_tag in your layout.
<%= stylesheet_link_tag 'one', 'two', :cache => "cache/all" %>
<%= javascript_include_tag 'jquery', 'ninja', :cache => "cache/all" %>
Priming the JS and CSS Caches
The Capistrano stuff is a bit tricky because Rails doesn’t generate the Javascript and CSS until after the app has been visited for the first time. So, you have to visit each of your web servers after restart during your deploy.
task :after_restart, :roles => :web do
desc "Visiting each web server"
sleep(5) # Wait for passenger to fully spin-up
run "/usr/bin/wget -O- http://127.0.0.1 >/dev/null 2>&1"
end
Invoking YUICompressor
Now, we can invoke YUICompressor after after_restart. The previous after_restart task automatically gets invoked after the web servers are restarted, however, the compression needs to happen after that. So, you have to manually chain a minify just after after_restart.
after "deploy:after_restart", "deploy:minify"
The actual task is quite simple for running the compressor itself. It’s just a normal Capistrano task.
task :minify, :roles => :web do
desc "Minify JS and CSS Using YUICompressor"
javascript = "#{current_path}/public/javascripts/cache/all.js"
stylesheet = "#{current_path}/public/stylesheets/cache/all.css"
compressor = "java -jar /usr/lib/java/yuicompressor-2.4.2.jar"
run "#{compressor} --type js #{javascript} -o #{javascript}"
run "#{compressor} --type css #{stylesheet} -o #{stylesheet}"
end






