如何在 Ruby 中的 YAML 文件中包含 YAML 文件 [英] How to include a YAML file inside a YAML file in Ruby

查看:56
本文介绍了如何在 Ruby 中的 YAML 文件中包含 YAML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 YAML 中是否有用于 ruby​​ 的自定义标记以在 YAML 文件中包含 YAML 文件?

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 question was asked some time ago and there was no relevant answer.

我想知道是否有一些类似于 this 的 Ruby 自定义标签Python.

I am wondering if there is some custom tag for Ruby similar to this one for Python.

推荐答案

我找到了一种使用 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. 最后一个包含覆盖同名键

这篇关于如何在 Ruby 中的 YAML 文件中包含 YAML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆