Read more

Convert primitive Ruby structures into Javascript

Henning Koch
April 30, 2012Software engineer at makandra GmbH

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}).

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2012-04-30 10:26)