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.

Ruby, Web | Comments | Trackback

2 Responses to “RJS Rails If statement”

  1. 1Paolo DonaNo Gravatar
    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!

  2. 2Enrico FranchiNo Gravatar
    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

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can keep track of new comments to this post with the comments feed.

Recent Posts

Blogroll

Siti amici

Misc

Recent Comments

Categories

Enrico Franchi graduated in Maths and Computer Science and is now studying for a Computet Science MSc (though because of italian bureaucracy that very course is to be cancelled).

RiK0's Tech Temple is using WP-Gravatar