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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)