Saturday, July 14, 2007

Asset Packager with Custom Rhino for super optimized JavaScript

Scott Becker has a wicked Javascript/CSS rails gem documented at:
http://synthesis.sbecker.net/pages/asset_packager

If like me, you have a stray missing semi-colon somewhere or would prefer to have the compression done in a compiled way as opposed to jsmin's regular expression substitution,

(note this requires a java runtime)

1. download DOJO shrinksafe's Custom Rhino jar from here into /vendor/plugins/asset_packager/lib

2. and then modify
/vendor/plugins/asset_packager/lib/synthesis/asset_package.rb as follows:
def compress_js(source)
#jsmin_path = "#{RAILS_ROOT}/vendor/plugins/asset_packager/lib"
custom_rhino_path = "#{RAILS_ROOT}/vendor/plugins/asset_packager/lib"
tmp_path = "#{RAILS_ROOT}/tmp/#{@target}_#{revision}"

# write out to a temp file
File.open("#{tmp_path}_uncompressed.js", "w") {|f| f.write(source) }

# compress file with JSMin library
#`ruby #{jsmin_path}/jsmin.rb <#{tmp_path}_uncompressed.js >#{tmp_path}_compressed.js \n`

cmd = "java -jar #{custom_rhino_path}/custom_rhino.jar -c #{tmp_path}_uncompressed.js > #{tmp_path}_compressed.js \n"
`#{cmd}`
...

PS. I havent yet chased up an easy way to rebuild the custom_rhino.jar with dojo's diff for newline stripping etc.