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

a 夏天 提交于 2019-11-30 12:37:07

问题


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

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

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

Settings.yml:

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

in rails console if I type

> ENV['FOOVAR']
=> WIDGET

but

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

回答1:


use following:-

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



回答2:


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

My .yml file contained something like:

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.




回答3:


Use <%= ENV['FOOVAR'] %> instead of <% 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.



来源:https://stackoverflow.com/questions/5866015/rails-3-how-use-an-env-config-vars-in-a-settings-yml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!