More complex inheritance in YAML?

后端 未结 3 1960
南方客
南方客 2021-01-31 02:00

YAML has inheritance. The most clear example I have ever seen is here: http://blog.101ideas.cz/posts/dry-your-yaml-files.html

I need something more complex: I need to ov

3条回答
  •  暖寄归人
    2021-01-31 02:18

    Unfortunately, you can't get the kind of "inheritance" you want to achieve because YAML's "inheritance" is more like a form of "merging hashes".

    Expanding out your configuration at the point you use the *default alias, you have:

    foo_database:
      server:
        ip: 192.168.1.5
        port: 2000
      db_name: test
      user: 
        name: root
        password: root
    

    If you use hashes with the same keys afterwards, they will completely overwrite the hashes declared earlier, leaving you with (excuse the formatting):

    foo_database:
    

      server:
        ip: 192.168.1.5
        port: 2000
      db_name: test
      user: 
       name: root
       password: root  
    

      server:
        port: 2001
      db_name: foo
      user:
        password: foo_root
    

    So, in your case, it would seem that since the config is not exactly the same, DRYing up your configuration using anchors and aliases probably isn't the right approach.

    More references on this issue below:

    • Rake, YAML and Inherited Build Configuration
    • Merging hashes in yaml conf files

    Edit

    If you really wanted to, I think you could reconfigure your YAML as below to get exactly what you want, but in your case, I would say the extra obfuscation isn't worth it:

    server_defaults: &server_defaults
      ip: 192.168.1.5
      port: 2000
    
    user_defaults: &user_defaults
      name: root
      password: root
    
    database: &default
      server:
        <<: *server_defaults
      db_name: test
      user: 
        <<: *user_defaults
    
    foo_database:
      <<: *default
      server:
        <<: *server_defaults
        port: 2001
      db_name: foo
      user:
        <<: *user_defaults
        password: foo_root
    

提交回复
热议问题