How can I get the equivalent of Rails.env.production? in application.js

Basically, I want the environment check to be done only in javascript, so I don't need to mutate my files using Rails.env.production? checks.

+4
source share
4 answers

The easiest way to do this, I believe, is to set the javascript variable to Rails.env, and then add the method to application.js to check it. The best place is probably in your layout, so in app/views/layouts/my_layout.html.erb something like:

 <script type="text/javascript"> var rails_env = '<%= Rails.env %>'; </script> 

What you can use in your javascript code.

+15
source

I just found out that putting JS in HTML files is a bad idea for many reasons, and you never need to.

So, the best way to solve this problem is to do this:

In your view (.erb) file:

 <div id="RAILS_ENV_CONSTANT" style="display:none"><%= Rails.env %></div> 

At the top of the application.js file:

 var RAILS_ENV = $('#RAILS_ENV_CONSTANT').text(); 
+5
source

I am not a fan of introducing a new variable, i.e. var rails_env = '<%= Rails.env %>' because it pollutes the global namespace. Do all JS files need this variable? Or all the features of JS?

I would use something similar to @Magne, but instead of creating a hidden div, I would just apply it to the body tag:

<body data-rails-env="<%= Rails.env %>">

Or in HAML (you use HAML, right ?!)

%body{ "data-rails-env" => Rails.env }

Then any script can pick it up:

$("body").data("rails-env")

+2
source

no, you cannot test your JS because JS is not a server. the easiest way is to create a JS file in relation to the environment and include it or make a variable from the template

0
source

Source: https://habr.com/ru/post/1382261/


All Articles