简体   繁体   English

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

[英]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? 我基本上只想在javascript中完成环境检查,所以我不必使用Rails.env.production丢弃我的视图文件? checks. 检查。

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. 我最简单的方法是将javascript变量设置为Rails.env的值,然后在application.js添加一个方法来检查它。 The best place is probably in your layout so in app/views/layouts/my_layout.html.erb something like: 最好的地方可能在你的布局中,所以在app/views/layouts/my_layout.html.erb就像:

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

Which you can then use in your javascript code. 然后您可以在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. 我刚刚了解到将JS放在HTML文件中是一个糟糕的主意,原因很多,而且不应该这样做。

So, the best way to solve this would be to do this: 因此,解决此问题的最佳方法是:

In your view (.erb) file: 在您的视图(.erb)文件中:

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

At the top of your application.js file: 在application.js文件的顶部:

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

I'm not a fan of introducing a new variable, ie var rails_env = '<%= Rails.env %>' because it pollutes the global namespace. 我不喜欢引入一个新变量,即var rails_env = '<%= Rails.env %>'因为它污染了全局命名空间。 Will all JS files need this variable? 所有JS文件都需要这个变量吗? Or all JS functions? 还是所有的JS功能?

I would use something similar to @Magne, but instead of creating a hidden div, I'd just apply it to the body tag: 我会使用类似于@Magne的东西,但不是创建一个隐藏的div,而是将它应用于body标签:

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

Or in HAML (You are using HAML, right?!) 或者在HAML中(你正在使用HAML,对吧?!)

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

Then any script can pick it up: 然后任何脚本都可以拿起它:

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

no you cant check in your JS because JS is not serversided. 不,你不能检查你的JS,因为JS不是服务器。 the onliest way is to generate a JS file in relation to the environment nad include it or make an variable from the template 最简单的方法是生成一个与环境相关的JS文件,包括它或从模板中创建一个变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM