Gon logo

Services & Skills

Share on

If you need to send some data to your JavaScript, and you don’t want to do this the long way through views and parsing:

An example of typical use

First, check out an excellent and detailed example and reasons to use Gon in a RailsCast by Ryan Bates.

When you need to send some data from your Rails controller to your JavaScript code, typically you might do something like this:

  1. Have the data ready in controller code assigned to a variable.
  2. In the Rails view for this action, you would use the data from that variable via data attributes—or write some JavaScript right in the view code.
  3. Next, in your JavaScript code, you would parse data attributes—or just use the data as is if you went with the inline JavaScript way.

With gon, you start with some configuration. Add gon to your Gemfile, and put a single tag in your layout. Now, you can:

  1. Pass variables using

    gon.variable_name = variable_value

    or, using a new syntax:

      :user_id => 1,
      :user_role => "admin"
    gon.push(any_object) # any_object with respond_to? :each_pair
  2. Within your JavaScript code, the variable would be accessible as


That’s it!

See also

You can easily renew data in your variables via AJAX with gon.watch.

gon-sinatra is available for using with Sinatra. There is also Jbuilder, Rabl, and Rabl-Rails support available.

There is a port for .Net MVC, called NGon.

For Phoenix, the Elixir web framework, check PhoenixGon.


In the same orbit

Explore more open source projects

Contact us

We’d love to hear from you! We’re not really all that evil, and we love discussing potential projects, intriguing ideas, and new opportunities. Complete the form below or drop us a line at surrender@evilmartians.com.

Martians at a glance
years in business

A product development consultancy that works with startups and established businesses, while also creating open source-based products and services