Javascript With Embedded Ruby: How To Safely Assign A Ruby Value To A Javascript Variable
Solution 1:
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)
Solution 2:
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 %>');
Solution 3:
@ruby_var.gsub(/[']/, '\\\\\'')
That will escape the single quote with an apostrophe, keeping your Javascript safe!
Also, if you're in Rails, there are a bunch of Javascript-specific tools.
Solution 4:
Could you just put the string in a double-quote?
res = foo("<%= @ruby_var %>");
Solution 5:
You can also use inspect assuming you know it'll be a single quote:
res = foo(<%= @ruby_var.inspect %>);
Post a Comment for "Javascript With Embedded Ruby: How To Safely Assign A Ruby Value To A Javascript Variable"