Bundle_fu + caching dynamic style sheets

On our hgl project we’ve been using dynamic style sheets and I wanted to add bundle_fu – since it makes a pretty big difference in page load times.

First – since I had a few gotchas getting dynamic style sheets working and then caching them here’s the code for that (this is all Rails 2.0):

First – the StyleSheetsController:

class StyleSheetsController < ApplicationController caches_page :sd, :sd2col, :sd3col def method_missing(method, *args, &block) respond_to do |format| format.html format.css end end end [/source] You should be able to do caches_page :method_missing but I couldn't get that to work, so I hard coded the style sheet names (which moderately defeats the purpose of method_missing, but, whatever) Now you can create views that use the usual rendering, variables, etc. Just call them mystylesheet.css.erb and they're only expensive the first time, then they're cached. Finally you need to add some restful routing stuff to routes. I have stylesheets sd.css, sd2col.css, and sd3col.css which need to route to /style_sheets/sd.css, etc. So, my routes.rb has this in it: [source:ruby] map.resources :style_sheets, :collection => {
:sd => :get,
:sd2col => :get,
:sd3col => :get,
:default => :get

This doesn’t work with bundle_fu (unless they’re already cached, which isn’t very elegant, and kind of confusing when you go to add new style sheets a month after you’ve forgotten all of this) because it is opening files and not actual urls. Bundle_fu has a param you can tack onto any url to have it just render things as normal and not do it’s magic. The hack I put it puts it in this mode if any of the files it’s trying to combine/compress are missing. Pretty simple:

In /vendor/plugins/bundle_fu/lib/bundle_fu.rb just paste this code before content = capture(&block) – around line 79 in method bundle

content.scan(/(href|src) *= *[“‘]([^”^’^\?]+)/i).each do |p,v|
if !(File.exists?(File.join(RAILS_ROOT, “public”,v)))
options[:bundle_fu] = false


mattJanuary 24th, 2008 at 7:22 pm

Once again, I’ve got to remark that this looks a lot like the cryptic perl code you used to scorn years ago… this is so far removed from a simple CSS file (or even a recognizable dynamic CSS file) that it’s not even funny.

And that you need to have an additional module just to make something as simple as dynamic stylesheets perform reasonably is kind of sad. What’s going on in rails??

KippJanuary 25th, 2008 at 10:37 pm

One man’s ruby is another man’s perl.

…I suppose that could be written with “woman” and it would still kind of make sense.