Gon

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:
    gon.push({
      :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
    gon.variable_name

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.

Author

In the same orbit

Explore more open source projects

How can we help you?

Martians at a glance
17
years in business

We transform growth-stage startups into unicorns, build developer tools, and create open source products.

If you prefer email, write to us at surrender@evilmartians.com