zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

RJS & MinusMOR

December 02, 2006 by nap · Comments

RJS rocks. It lets me write JavaScript without writing any JavaScript. That’s very Zen, and I like it. But sometimes I find myself writing really ugly, narsty things in my RJS templates. Instead of using Ruby to write JavaScript I end up writing JavaScript and appending it to the page with Ruby, especially when client side conditionals are involved. Needless to say, the template code quickly devolves into what can only be described as frankenrubyscript.

To rid ourselves of the monster, take a look at Dan Webb’s MinusMOR plugin, which lets you return plain ol JavaScript to the browser using templates with an .ejs file extension. This may not seem like a big deal but it’s pretty damn helpful if you return any significant amount of client-side logic within RJS.

[Note that you’ll need to be on the Rails 1.2 codebase to use the plugin]

As a simple example, let’s overhaul our sample YUI test app to use MinusMOR. Now this really isn’t a great example, as the JavaScript code is super simple and therefore lends itself well to being written in Ruby. But oh well. At least it gives you an idea of how it works.

Our add.rjs file used to contain the following one-liner:

page.replace_html 'hello_msg', @thing[:name]

Now, our add.ejs file will contain the following code instead. Note the use of ERb in the template:

document.getElementById('hello_msg').innerHTML = '<%=@thing[:name]%>';

In this case the normal RJS approach is quicker, sexier, and, above all else, easier to read. And, admittedly, 90% of your client-side code will more than likely be the simple kind of stuff that RJS rocks at (update this text within that DIV, switch the visible state of that DOM element to hidden, etc). But you can certainly imagine scenarios where it’d make sense to write pure JavaScript in the template instead.

Use RJS wherever you can, but once bits and pieces of frankenrubyscript start sneaking into your code, be sure to check out Dan’s plugin. Cuz there’s no denying that there are cases where using plain ol JavaScript is cleaner, as un-Zen-like as that may seem….!

blog comments powered by Disqus