Jacob's Programming Explosions

Going, Going, Gon

This post is about passing variables from your rails controller to your javascript files.

Recently, I was working on a rails project involving some javascript on the front end. Javascript is fun, so I was excited to get started on it. The feature was going to be a set of charts (using the chart.js library) populated with data relating to a group of users. It didn’t take me long to figure out that while it is super easy to pass data from a controller to a view, I didn’t actually know how to pass anything from my controllers to my javascript files. I tinkered around for a bit without any success. At one point I started to consider the ridiculous idea of firing an AJAX GET request back to my controller on page load using JQuery to get what I needed, since I already knew how to do that. But that felt really dirty, and I’m a little embarrassed to even mention it.

Then my friend Amy told me to use Gon.

Gon? It’s a sweet gem for passing variables from your rails controller to your javascript files. Just what I needed! Gon is incredibly easy to use. I’ll show you.

  1. First, add Gon to your Gemfile (and run bundle install). Now add <%= include_gon %> in the <head></head> section of application.html.erb. Now you are ready to get down to business!

  2. In the appropriate controller and action, we’re going to create a variable for the data you want to pass to the js file. Here I’m in groups_controller.rb in the show action. This action is responsible for a single group’s page (ie example.com/groups/3). This action renders /app/views/groups/show.html.erb, inside of which I include my javascript file via a javascript_include_tag (/app/assets/javascripts/groups_show.js). All you need to do is name your variable like so: gon.your_variable_name.

groups_controller.rb

1
2
3
4
def show
  @group = Group.find(params[:id])
  gon.group_name = @group.name
end
  1. That’s it! gon.group_name is now available in my groups_show.js file.

groups_show.js

1
2
var groupName = gon.group_name
// That was really easy.

As you can see, Gon is a super useful and easy way to pass data from you controllers to your javascript files.