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:
Ex:-

HTML:

;
$('#user').val();


HTML data attribute:

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

$(‘#posts’).data(‘posts’);


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.


Setup

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'

#or

gon.push({
	currentUser: @user,
	title: 'Sample Gon''
})

So, in javascript we can use them as normal variables

console.log(gon.currentUser);  
console.log(gon.title);

Notes:
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(https://github.com/gazay/gon/wiki/Options).
Gon can be used with jbuilder and rabl(https://github.com/gazay/gon/wiki)
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 gon.watch. Please check official gon documentation for more information.


Resources:

https://github.com/gazay/gon

Check out this article on our Facebook Page : https://www.facebook.com/RailsCarma

Related Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish