you're reading...
Javascript with RoR

Assigning a Ruby expression to a Javascript variable.

I came across a problem: before directly assigning a ruby expression to a javascript variable, it’s a good idea to escape it:

var my_javascript_var = '<%= escape_javascript(my_ruby_expression) %>';

The reason to do that is your ruby expression might contain special symbols ( for example some innocent quotes), making your life excruciatingly painful when all of your javascript code stops working.

This was a direct assignment. However, if you assign a javascript variable using PrototypeHelper, don’t escape your ruby expression! If you use:

page.assign 'my_javascript_var', escape_javascript(my_ruby_expression)

you will see your code’s html guts on the page.

In this case you need to use:

page.assign 'my_javascript_var', my_ruby_expression

The expression has been already escaped for you by Ruby on Rails.


About RailsBlogger

I'm a Software Developer with over 10 years of experience, Java and Ruby on Rails.


No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ip tracing
%d bloggers like this: