Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I basically want to have the environment check done in javascript only, so I don't have to litter my view files with Rails.env.production? checks.

like image 807
Magne Avatar asked Nov 29 '22 03:11

Magne


2 Answers

The easiest way to do this I believe is to set a javascript variable to the value of Rails.env and then add a method in 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>

Which you can then use in your javascript code.

like image 89
Shadwell Avatar answered Dec 07 '22 00:12

Shadwell


I just learned that putting JS in HTML files is a bad idea for lots of reasons, and one should never need to do so.

So, the best way to solve this would be to do this:

In your view (.erb) file:

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

At the top of your application.js file:

var RAILS_ENV = $('#RAILS_ENV_CONSTANT').text();
like image 25
Magne Avatar answered Dec 07 '22 01:12

Magne