From: Kirk Haines Date: 2005-10-06T05:21:19+09:00 Subject: Re: CSS switcher in Ruby? On Tuesday 04 October 2005 10:17 pm, Tom Cloyd wrote: > I have no idea if this is a goofy idea or not (and I'm only just starting > with Ruby and unable to attempt this project myself), but might a CSS > switcher for web pages be possible in Ruby? Seems quite possible to me, > but... Possible, and generally easy, though the details depend a great deal on what environment one is running one's web stuff in. I have two approaches. One approach is for occasions where there may be both static and non-static pages that all need to have some intelligent stylesheet selection. Often I use this just to have a special stylesheet for browsers that say they are IE, so that I don't have to deal with gross box model hacks and other pain involved in making a single stylesheet work with, say, IE and Firefox. A version of the code I use for this style would look something like this: class Styles < Iowa::Component @@styles_mtimes = {'styles.css' => 0, 'styles_nonie.css' => 0} @@styles = {} def styles session.context.request.content_type = 'text/css' begin headers = session.context.request.headers_in['User-Agent'] # A very naive browser type check follows. style_file = header =~ /MSIE/ ? 'styles.css' : 'styles_nonie.css' if File.stat(style_file).mtime.to_i > @@styles_mtimes[style_file] @@styles[style_file] = File.read(style_file) @@styles_mtimes[style_file] = File.stat(style_file).mtime.to_i end rescue Exception # Something bad happened. Do something? end @@styles[style_file] end end A variation of this could easily be used to select a stylesheet based on a cookie value, for more sophisticated CSS file switching. The other approach that I use occasionally is to embed the logic at the other end, in the code that generates the original HTML page. css_url would be a method that would return the URL to the desired CSS file. One obvious problem with this method is that it requires that the HTML page be dynamically generated. Having a smart /styles.css delivery, on the other hand, means that even static HTML files can be served different stylesheets based on browser type or a cookie or some other trait, and that's how I usually approach this issue. The browser never knows that the response from a request for /styles.css is being dynamically generated. Kirk Haines