Mag*_*gne 4 javascript ruby-on-rails
我基本上只想在javascript中完成环境检查,所以我不必使用Rails.env.production丢弃我的视图文件?检查.
Sha*_*ell 15
我最简单的方法是将javascript变量设置为Rails.env的值,然后添加一个方法application.js来检查它.最好的地方可能是你的布局,所以在app/views/layouts/my_layout.html.erb这样的:
<script type="text/javascript">
var rails_env = '<%= Rails.env %>';
</script>
Run Code Online (Sandbox Code Playgroud)
然后您可以在javascript代码中使用它.
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>
Run Code Online (Sandbox Code Playgroud)
At the top of your application.js file:
var RAILS_ENV = $('#RAILS_ENV_CONSTANT').text();
Run Code Online (Sandbox Code Playgroud)