Use of Gon Gem with Javascript & Rails

Using Rails data as a part of javascript is an extremely regular need, particularly for Javascript applications such as Angular, Ember and SPA.

If it is a small amount of data, we can directly assign it to the ruby variables.

From rails view:



HTML data attribute:

<%= content_tag "div", id: "posts", data: {posts: Post.limit(5)} do %>
  Loading ..
<% end %>;
Loading ..


From rails controllers by using Gon:

Above scenarios appear to be not spotless and sensible, particularly when we require more information rather than just some data.

Actually, there is a good solution for passing Rails variables from controllers to javascript i.e gon gem.

Gon helps us to fullfil our need in an easier and cleaner manner.


It is quite easy to set up gon gem.

Add gem ‘gon’ to Gemfile and run bundle install
Insert <%= include_gon %>; in head tag of layouts/application.html.erb. You can place it anywhere you wish to use. Move it to the particular view if you wish to use in that particular view only.

Set variables from controller/view (mostly from controllers)

gon.currentUser = @user
gon.title = 'Sample Gon'


	currentUser: @user,
	title: 'Sample Gon''

So, in javascript we can use them as normal variables


We can modify the variable namespace. This means, we can user app.variableName instead of gon.variableName. But we need to specify namespace when including.

<%= include_gon(namespace: 'app') %>;

There are other lists of options we can set for gon(
Gon can be used with jbuilder and rabl(
Push at least one variable to gon to prevent gon in not defined error otherwise validate if it is defined or not.
Gon variables can be reloaded from rails by using Please check official gon documentation for more information.


Check out this article on our Facebook Page :

Articles Similaires

Laissez un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *