Ruby-on-rails rails 3,如何在 Settings.yml 文件中使用 ENV 配置变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5866015/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:04:44  来源:igfitidea点击:

rails 3, how use an ENV config vars in a Settings.yml file?

ruby-on-railsyamlenv

提问by jpw

In my settings.yml file I have several config vars, some of which reference ENV[] variables.

在我的 settings.yml 文件中,我有几个配置变量,其中一些引用了 ENV[] 变量。

for example I have ENV['FOOVAR'] equals WIDGET

例如我有 ENV['FOOVAR'] 等于 WIDGET

I thought I could reference ENV vars inside <% %> like this:

我以为我可以像这样在 <% %> 中引用 ENV 变量:

Settings.yml:

设置.yml:

default:
   cv1: Foo
   cv2: <% ENV['FOOVAR'] %>

in rails console if I type

如果我输入,在 rails 控制台中

> ENV['FOOVAR']
=> WIDGET

but

> Settings.cv1
=> Foo   (works okay)
> Settings.cv2
=>nil   (doesn't work???)

回答by Anubhaw

use following:-

使用以下:-

 default:
       cv1: Foo
       cv2: <%= ENV['FOOVAR'] %>

回答by arpiagar

The above solution did not work for me. However, I found the solution on How do I use variables in a YAML file?

上述解决方案对我不起作用。但是,我找到了有关如何在 YAML 文件中使用变量的解决方案

My .yml file contained something like:

我的 .yml 文件包含如下内容:

development:
gmail_username: <%= ENV["GMAIL_USERNAME"] %>
gmail_password: <%= ENV["GMAIL_PASSWORD"] %>

The solution looks like:

解决方案如下:

template = ERB.new File.new("path/to/config.yml.erb").read
processed = YAML.load template.result(binding)

So when you introduce a scriptlet tag in .yml file, it is more of erb template. So read it as a erb template first and then load the yml as shown above.

所以当你在 .yml 文件中引入 scriptlet 标签时,它更像是 erb 模板。所以先把它读成erb模板,然后如上图加载yml。

回答by PreciousBodilyFluids

Use <%= ENV['FOOVAR'] %>instead of <% ENV['FOOVAR'] %>.

使用<%= ENV['FOOVAR'] %>代替<% ENV['FOOVAR'] %>

Be aware that this approach will only work if whatever is parsing the Yaml file is set up to process it via Erb (for example, you can see how Mongoid does exactly this). It's not universally supported in Yaml files though, so it depends on what you're using this Yaml file for.

请注意,这种方法仅在解析 Yaml 文件的任何内容设置为通过 Erb 处理它时才有效(例如,您可以看到Mongoid 是如何做到这一点的)。不过,它在 Yaml 文件中并未得到普遍支持,因此这取决于您将此 Yaml 文件用于什么目的。