Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript with embedded Ruby: How to safely assign a ruby value to a javascript variable

I have this line in a javascript block in a page:

res = foo('<%= @ruby_var %>'); 

What is the best way to handle the case where @ruby_var has a single-quote in it? Else it will break the JavaScript code.

like image 529
Yoni Baciu Avatar asked Sep 20 '08 00:09

Yoni Baciu


2 Answers

I think I'd use a ruby JSON library on @ruby_var to get proper js syntax for the string and get rid of the '', fex.:

res = foo(<%= @ruby_var.to_json %>)

(after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language)

(on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)

like image 178
TFKyle Avatar answered Oct 04 '22 22:10

TFKyle


Rails has method specifically dedicated to this task found in ActionView::Helpers::JavaScriptHelper called escape_javascript.

In your example, you would use the following:

res = foo('<%= escape_javascript @ruby_var %>');

Or better yet, use the j shortcut:

res = foo('<%= j @ruby_var %>');
like image 30
Mike Jarema Avatar answered Oct 04 '22 21:10

Mike Jarema