yml文件在默认情况下运行

时间:2013-01-18 16:18:58

标签: ruby yaml

我的config.yml文件看起来像这样

development: &development
  <<: *development
  sub1:
    sub11: "myemail@fiverr.com"
    sub12: "http://localhost"

staging:
  <<: *development
  sub1:
    sub12: "http://google.com"

production:
  <<: *development
  sub1:
    sub12: "http://youtube.com"

我像这样加载

SETTINGS = YAML::load(File.open( "#{ROOT}/config/config.yml")).with_indifferent_access[ENV['RACK_ENV']] unless defined?(SETTINGS)

事情是在开发环境中:

SETTINGS[:sub1][:sub12] = "http://localhost"
SETTINGS[:sub1][:sub11] = "myemail@fiverr.com" 

和staging env:

SETTINGS[:sub1][:sub12] = "http://google.com"
SETTINGS[:sub1][:sub11] = "nil" 

似乎如果我没有定义它,它就消失了!

1 个答案:

答案 0 :(得分:1)

当你有:

staging:
  <<: *development
  sub1:
    sub12: "http://google.com"

您合并了development地图中的密钥,然后将sub1密钥的值设置为新的sub12映射。请注意,这将替换从开发映射合并的整个原始sub1映射。映射以递归方式合并。

它相当于纯Ruby中的类似内容:

development = {'sub1' =>
  {'sub11' => "myemail@fiverr.com", "sub12" => "http://localhost"}
}

staging = {}
staging.merge! development
staging["sub1"] = {"sub12" => "http://google.com"}

并且实际上是implemented in pretty much this way in Psych(Ruby的Yaml库)。

要修复它,您需要将锚点添加到子哈希中:

development:
  sub1: &sub1defaults
    sub11: "myemail@fiverr.com"
    sub12: "http://localhost"

staging:
  sub1:
    <<: *sub1defaults
    sub12: "http://google.com"

production:
  sub1:
    <<: *sub1defaults
    sub12: "http://youtube.com"

不幸的是,如果您的配置中有许多这样的嵌套映射,这可能会涉及更多工作。