How to include a YAML file inside a YAML file in Ruby

后端 未结 7 1317
悲&欢浪女
悲&欢浪女 2020-12-28 16:13

Is there a custom tag in YAML for ruby to include a YAML file inside a YAML file?

#E.g.:  
--- !include
filename: another.yml

A similar que

相关标签:
7条回答
  • 2020-12-28 17:10

    I found a way to address my scenario using ERB.

    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
    

    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") %>
    

    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
    

    Caveats:

    1. Does not support document merge
    2. Last include overwrites same named keys
    0 讨论(0)
提交回复
热议问题