How To Write Code
That Doesn't Suck

wry observations from the deep end of the software cesspool


Server-Side View Source for Rails

I often find, particularly early in projects, that I need to spend more time looking at the HTML source of a page rather than the page itself, e.g. when trying to get the correct javascript or css files included. All browsers offer some sort of "view page source" option, but this opens another window, and there's no way to directly refresh the page as you update it. After a few iterations I'm usually left with more than one source window open and no easy way to tell which is the latest. This problem had me thinking about a server side view source solution, and thanks to Rails controllers' after_filter it turns out to just take one line:

Throw this in a controller and instead of the normal pages you'll see the source in your browser, e.g.

Covers my basic need: no extra clicks to refresh, no getting lost in multiple popup windows, and since it's one line easy to turn on/off by commenting out. However in one important regard it's step backwards from Firefox's View Page Source: it lacks syntax highlighting. I had a couple thoughts about how to tackle this, and Google revealed some earlier attempts to pretty-print HTML in Ruby. I toyed with this approach for a few minutes before deciding it was heading way down the too-much-complexity path, particularly for a hacky development-only feature. Taking another look at that blog post something struck me--there's nicely formatted code right there in the post, thanks to Alex Gorbatchev's client-side javascript/css syntax highlighter. Alex kindly offers a hosted version of the needed files, which allows for extending the one line approach without adding any dependencies.

Which yields the much prettier result

Since it's no longer so easy to turn on and off via comments (Ruby's lack of a multi-line comment form is one of my main gripes with the language) I threw in a hack to turn it on and off by tacking VS onto the end of the URL (it should usually be harmless to do this as an extra param, e.g. ?VS or &VS).


Post a Comment