如何在rails app中的javascript文件中获取环境

时间:2022-01-03 23:49:53

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...

你好香港专业教育学院一直试图让当前的环境在铁路,但我认为我做了一些错误的我的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

即使我处于开发模式,它总是会进入我的声明。我究竟做错了什么?谢谢

how to get environment in javascript file in rails app

如何在rails app中的javascript文件中获取环境

2 个解决方案

#1


11  

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.

这里有对预处理器的扩展讨论。

#2


38  

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')

#1


11  

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.

这里有对预处理器的扩展讨论。

#2


38  

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')