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

Let's solve your hard problems

Martians at a glance
18
years in business

We're experts at helping developer products grow, with a proven track record in UI design, product iterations, cost-effective scaling, and much more. We'll lay out a strategy before our engineers and designers leap into action.

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