Very often, I have come accross the situation where I need ruby variables in javascript file. Recently, I got to know about a wonderful gem gon which does the work for you. Lets see with an example.

Include gem in your Gemfile and bundle install. Write gon variables in rails controller as

  gon.variable_name = variable_value

gon should be included in the html pages, wherever required. Better to include in application.html.erb. Include gon as

  <%= include_gon %>

Here, value can be of any data type, you can use the variables in javascript as

  var variableName = gon.variable_name

You can also add a namespace as

  <%= include_gon namespace: 'domain_name'%>

For using the variables in javascript with namespaced variables

  var variableName = domain_name.variable_name

References: gon