# Gon

> A Ruby gem that provides a straightforward way to pass Ruby variables to the Rails frontend code.

- URL: https://evilmartians.com/opensource/gon
- GitHub: https://github.com/gazay/gon
- Authors: Alexey Gaziev

---

Gon is a popular Ruby gem that provides a straightforward way to pass Ruby variables to the frontend code of your Ruby on Rails application. Additionally, several ports to other frameworks and languages are available.

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](http://railscasts.com/episodes/324-passing-data-to-javascript) 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
   ``` ruby
   gon.variable_name = variable_value
   ```
   or, using a new syntax:
   ```ruby
   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
   ``` js
   gon.variable_name
   ```

That's it!

## See also

You can easily renew data in your variables via AJAX with [gon.watch](https://github.com/gazay/gon/wiki/Usage-gon-watch).

[gon-sinatra](https://github.com/gazay/gon-sinatra) is available for using with Sinatra. There is also [Jbuilder](https://github.com/rails/jbuilder), [Rabl](https://github.com/nesquena/rabl), and [Rabl-Rails](https://github.com/ccocchi/rabl-rails) support available.

There is a port for _.Net MVC_, called [NGon](https://github.com/brooklynDev/NGon).

For _Phoenix_, the _Elixir_ web framework, check [PhoenixGon](https://github.com/khusnetdinov/phoenix_gon).
