Using gon in rails to pass data to javascript
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
should be included in the html pages, wherever required. Better to include in application.html.erb
. Include gon as
Here, value can be of any data type, you can use the variables in javascript as
You can also add a namespace as
For using the variables in javascript with namespaced variables
References: gon