Reputation: 588
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
or
Upvotes: 12
Views: 635
Reputation: 2401
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.
Upvotes: 0