我怎样才能得到Rails.env.production的等价物?在application.js中

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代码中使用它.

  • @unclenorton:是的,我知道,但为什么它会更加防弹呢? (5认同)

Mag*_*gne 5

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)