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.
Using the Gon gem to pass data from the server to the client is a common practice in Ruby on Rails applications, but it does have some drawbacks.
One potential issue is that it can make your JavaScript code harder to test and debug, as it relies on the Gon gem to set certain variables in the global scope. Additionally, it can also make it harder to understand the flow of data in your application, as the variables passed from the server to the client are not explicitly defined in the JavaScript code.
An alternative approach would be to use an AJAX call to retrieve the data from an endpoint on the server, or to set the data in a cookie and read it from the JavaScript. Both of these approaches have their own advantages and disadvantages, but they may be more suitable for larger and more complex applications.
It's worth noting that, when working with sensitive data such as user-specific data, it's important to keep in mind the security implications of each approach and make sure that sensitive data is not exposed in ways that could compromise the security of your application.
Ultimately, the best practice will depend on the specific requirements and constraints of your application. It's a good idea to evaluate different options and choose the one that best fits your needs.