From Rails Controller to Javascript
Ever had to send some information from your Rails controller to your javascript? If so then you've probably had to add a pesky Javascript tag into your erb or HAML in order to get the information though. I recently cam across a gem called Gon from a RailsCast which allows a more direct way to send data from controller to Javascript. Simply include the gem in your Gemfile:
gem 'gon'
then toss
<%= include_gon %>
into the title of your application.html.[erb || haml] and now you can access the 'gon' variable within your controller and its associated js.coffee file. It is also recommended that you always check iof the gon variable is set within your Coffeescript before you use it.
Thanks to RailsCasts for creating a great intro to Gon, and I hope that it can be of use to someone.
Written by Sylvester Willis
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside