javascript 如何在rails应用程序的javascript文件中获取环境
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10440853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get environment in javascript file in rails app
提问by david
hello ive been trying to get the current environment in rails but i think im doing something wrong with my javascript, but i dont seem to know what. in my application.js i have...
你好,我一直试图在 Rails 中获取当前环境,但我认为我的 javascript 有问题,但我似乎不知道是什么。在我的 application.js 我有...
var rails_env = '<%= Rails.env -%>';
alert(rails_env);
alert(rails_env.value);
if(rails_env == 'development'){
alert('inside if')
var indexName = "idx";
}
else{
alert('inside else')
var indexName = "idx_production";
}
it always goes into my else statement even if i am in development mode. what am i doing wrong? thank you
即使我处于开发模式,它也总是进入我的 else 语句。我究竟做错了什么?谢谢
how to get environment in javascript file in rails app
如何在rails应用程序的javascript文件中获取环境
回答by Matthew
You dont need to pass it into your javascript file directly. You can do it in the erb
view file like this for example:
您不需要直接将它传递到您的 javascript 文件中。您可以在erb
视图文件中执行此操作,例如:
<script>
window._rails_env = "<%= Rails.env %>"
</script>
or better this:
或者更好:
<%= javascript_tag do %>
window._rails_env = "<%= Rails.env %>"
<% end %>
or the best (IMHO) this:
或最好的(恕我直言)这个:
<body data-env="<%= Rails.env %>">
...
and then:
接着:
var railsEnv = $('body').data('env')
Warning:
警告:
Dumping your entire Rails environment in script like this will almost certainly compromise your web app's security! As Micha? Zalewski mentions in a comment below, your Rails application has sensitive information in its environment, like database credentials, API keys, application secrets for signing and encrypting cookies etc.
像这样在脚本中转储整个 Rails 环境几乎肯定会危及 Web 应用程序的安全性!作为米夏?Zalewski 在下面的评论中提到,您的 Rails 应用程序在其环境中具有敏感信息,例如数据库凭据、API 密钥、用于签名和加密 cookie 的应用程序机密等。
回答by rjz
Rails' asset pipeline will only preprocess assets that you mark for parsing. Whether those assets are going to end up CSS, JS, or whatever else, you can mark files for parsing by adjusting the file extension.
Rails 的资产管道只会预处理您标记为要解析的资产。无论这些资产最终是 CSS、JS 还是其他任何东西,您都可以通过调整文件扩展名来标记要解析的文件。
In this case, where you're trying to output an ERB variable, you will need to change the extension of the file to application.js.erb
.
在这种情况下,当您尝试输出 ERB 变量时,您需要将文件的扩展名更改为application.js.erb
.
There's an extended discussion of the preprocessor here.
有预处理器的扩展讨论这里。