Every so often one has the desperate need beat RJS into evaluating javascript conditionals, say, if you don’t know if an element is going to necessarily be on the page or not.

For this one particular use case, luckily, Enrico Franchi pointed out a workaround for this.


page.select('element').each do |element|
  page.replace_html element, replacement
end

But what if we want to compare equality, or any other type of conditional? We can use the unbelievably, ridiculously, mind bogglingly ugly hack:


page << 'if (el.value == 10) {'
  page['block'].replace_html replacement
page << '} else {'
  page['block'].replace_html replacement
page << '}'

Imagine if we needed both of these previous methods combined? My head is spinning!

Dann Webb provides a plugin that implements ejs (erb based javascript) that provides a very cool and interesting mesh between javascript and erb.

But tell me. Why, oh why, wasn’t this patch accepted?

One Response to “Javascript Conditionals in RJS”

  1. Udgin Says:

    "Why wasn’t this patch accepted?" – really very nice question ;)
    I have no words to say :)


Leave a Reply