Ruby on Rails Gon Gem vs. cookies or regular AJAX request

631 Views Asked by At

I've been programming on Ruby on Rails for a while now, and to be able to easily access data from my controllers in my javascript code, as a beginner I came across the Gon Gem. It solves the problem quite simply, but a bit mysteriously to the RoR beginner, to be honest.

Diving into the gem's source code, I now understand how it works: The variables you ask gon to pass on to your JS are tracked by the gem and inserted into a <script /> tag on your view rendered by the erb tag

<%= Gon::Base.render_data %>

which makes the gon object available across your JS since it injects it as a window property.

My question is, how good of practice is this? Quite frankly it seems a bit fishy to dynamically inject JS code into a site just to access some data from the server in the browser. Wouldn't it be a better practice to either

  • Just make the data available via an endpoint on the RoR server side and an AJAX call from the JS frontend.

or

  • Set the needed data on a cookie during the corresponding action on the RoR controller and just read it from the JS.
1

There are 1 best solutions below

0
On

Meh.

It's a matter of how many calls you want, how big your data is, how many gon features you want to use (the updates, etc). There are plenty of wrongs ways to do things. There are a few ways that are right. gon is great for some use cases - especially apps that are migrating from HTML to heavy js usage.