且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ruby 中的 YAML 文件中包含 YAML 文件

更新时间:2022-01-30 23:01:52

我找到了一种使用 ERB 解决方案的方法.

I found a way to address my scenario using ERB.

我修改了 YAML 模块以添加两个新方法

I monkey patched YAML module to add two new methods

module YAML
    def YAML.include file_name
      require 'erb'
      ERB.new(IO.read(file_name)).result
    end

    def YAML.load_erb file_name
      YAML::load(YAML::include(file_name))
    end  
end

我有三个 YAML 文件.

I have three YAML files.

mod1_config.yml

mod1:
    age: 30
    city: San Francisco

mod2_config.yml

mod2:
    menu: menu1
    window: window1

all_config.yml

<%= YAML::include("mod1_config.yml") %>
<%= YAML::include("mod2_config.yml") %>

使用方法 YAML::load_erb 而不是方法 YAML::load 解析 yaml 文件.

Parse the yaml file using the method YAML::load_erb instead of the method YAML::load.

  config = YAML::load_erb('all_config.yml') 
  config['mod1']['age'] # 30
  config['mod2']['menu'] # menu1

注意事项:

  1. 不支持文档合并
  2. 最后一个包含覆盖同名键