RailsCasts Pro episodes are now free!

Learn more or hide this

Josh Whiting's Profile

GitHub User: jwhiting

Site: http://blog.yetanotherjosh.com/

Comments by Josh Whiting

Avatar

Actually, furthermore you really should be adding a to_s on @foo:

var foo = '<%= j @foo.to_s.html_safe %>';

Because if there's any chance @foo might not be a string, you'll get a NoMethodError trying to call html_safe on it.

I'm gonna go out on a limb here and wager that most Rails devs are not applying these three (count 'em, three) conversions on their values in order to splat them into a script?

Avatar

It seems to me this railscast is presenting the incorrect way to put content into javascript variables.

If you are trying to put a template variable into a javascript variable inside an HTML template, the syntax is actually not very intuitive:

var foo = '<%= j @foo.html_safe %>';

You have to flag the string as safe for raw output into the html document, but also apply javascript escaping. Otherwise, if @foo contains "<foo>" then your final document output will be:

var foo = '&lt;foo&gt;';

Which is almost certainly not what you want.

However, if you use html_safe but forget to apply the javascript escaping, you are opening yourself seriously to javascript injection attacks. So this is stuff that must be done very carefully in order to be done both correctly and safely.

IMO it is unfortunate that apparently no authoritative documentation or respected tutorials point this nuance out, and that Rails has no better, more intuitive way to put content safely and correctly into javascript strings...