Convert primitive Ruby structures into Javascript

Posted . Visible to the public.

Controller responses often include Javascript code that contains values from Ruby variables. E.g. you want to call a Javascript function foo(...) with the argument stored in the Ruby variable @foo. You can do this by using ERB tags (<%= ruby_expression %>) or, in Haml, interpolation syntax (#{ruby_expression}).

In any case you will take care of proper quoting and escaping of quotes, line feeds, etc. A convenient way to do this is to use Object#json Show archive.org snapshot , which is defined for Ruby strings, numbers, arrays and hashes:

Tree.init({
  path: <%= tree_url(@tree).to_json %>,
  child_ids: <%= @tree.child_ids.to_json %>
});

The output of #to_json will be properly quoted and escaped. There is no need to wrap it with your own quotes.

Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2012-04-30 08:26)