If you're like me, you tried to do this:
if(Element.visible('free_beer'))
page.hide('free_beer')
end
because we (of course) want to hide our free beer as quickly as possible if it's visible. You may not have gone as far as I did (actually running the request and being sad) but I'm sure you realized there's no really good way to put if statements cleanly into RJS.
Finally, here come the RJS-if patch (which means more free beer)
Simply add a page. in front of that if and put quotes around the conditions and you got yourself some real, outputting, javascript ifs.
page.if("Element.visible('free_beer')") {
page.hide('free_beer')
}.elsif("Element.visible('free_accordians')") {
page.visual_effect(:highlight, 'free_accordians')
}.else {
page['header'].replace_html "sorry, nothing free today"
}
Now you can keep your beer, get rid of your accordians, and do it all cleanly.
The syntax is similar to javascript ifs, else if, and else. The only change is the . after the closing '}' to call the next method (elsif or else).
This patch comes complete with tests that proove it will protect your beer.
Ok, I like beer, but how's it work?
It works by adding an if and unless method to the JavaScriptGenerator::GeneratorMethods module.
I also added a class called ConditionChain to JavaScriptGenerator::GeneratorMethods that is explicitly for return from an if, unless, or elsif block. This way we can control what methods are available to chain onto an if. Only elsif and else may be added on to an if, elsif, or unless statement which makes sure that we're writing good code (and get a reasonable error instead of just outputting weird javascript if we happen to be dumb)