views:

648

answers:

4

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.

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

A: 

1) '!include' is not a directive but a tag

2) it is not a feature of Python (or PyYAML) but a feature of the "poze" library:

poze.configuration exposes a default directive named include.

3) YAML specification does not define such a standard tag

YAML spec doesn't have the tag `!include`. I was hoping that somebody has written a custom tag similar to the custom tag in "poze" library. I guess its time to write the custom tag myself :-)
KandadaBoggu
+1  A: 

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.xml') 
  config['mod1']['age'] # 30
  config['mod2']['menu'] # menu1

Caveats:

  1. Does not support document merge.
  2. The include directive has to be at the top of the file.
KandadaBoggu
A: 

Depends what you need it for. If you need to transport file, you can base64 encode internal yaml file.

Rubycut
A: 

If your aim is avoiding duplication in your YAML file, not necessarily including external file, I recommend doing something like this:

development: &default
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: db_dev
  pool: 5
  username: usr
  password: psw
  host: localhost
  port: 3306

dev_cache:
  <<: *default

new:
  <<: *default
  database: db_new

test:
  <<: *default
  database: db_test
skalee