RJS Rails If statement
June 14th, 2006
If you do something like:
page.replace_html 'non_existent', 'some text'
you get a Javascript error and sequent lines are not processed. The first idea to solve this problem would be
if page['not_valid'] page.replace_html 'not_valid', 'some text' end
However, you don’t get what you meant. Not at all. This is translated to
$("not_valid")
Element.update("not_valid", "some text");
The best way I found do express that meaning is
page.select('not_valid').each do |unique|
page.replace_html unique, 'some text'
end
That works.
2 Responses to “RJS Rails If statement”
1Paolo Dona
June 15th, 2006 @ 06:06
Hey man, that’s weird. Shouldn’t this be fixed by the rails community? I haven’t crashed into this but I’m shure I would have lost a lot of time trying for it. This suggest me no “if” statement will be translated in js.. am I wrong?
When is it translated and when it is not?
PS: great hint!
2Enrico Franchi
June 15th, 2006 @ 17:43
In fact since rjs are templates that are preprocessed it makes sense:
The ruby if clause is evaluated and not “translated”.
In fact it “understands” lots of things (for example)
page.assign :re, Regexp.new(”someregexp”)
works as expected
re = /someregexp/;
However, there are no if statements. Loops are provided throught the mapping
some_array.each do
rubycode
end
some_array.each(function(value, index) { translated ruby_code });
I am quite surprised too… however a good old
page << “if (javascript_condition) {”
ruby code
page << “}”
does the dirty job (but when possible I tend to avoid such a “dirty” solution)
Leave a Reply