0

I have YAML file with inheritance and I want to add or edit a key programatically. I load the YAML into hash using YAML.load method but when I save the hash back using YAML.dump I lose all the inheritance info.

Is there a way to edit the YAML in Ruby without losing the inheritance info?

YAML example:

main:
  prod: &prod
    key1: true
    key2: 50
    key3: "abc"

  prod_v_3_5: &prod_v_3_5
    <<: *prod
    key2: 100


  prod_v_3_6: &prod_v_3_6
    <<: *prod_v_3_5
    key2: 150

Code example:

config = Api.get(id)
yaml = YAML.load(config)
yaml["main"][section].store(key, value)
config = YAML.dump(yaml)
Api.set(id, config)
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Johnathan Kanarek
  • 834
  • 1
  • 10
  • 16
  • please share example file you want to edit and some code which you tried but failed. – Md. Farhan Memon May 03 '17 at 10:06
  • The [YAML specification](http://yaml.org/spec/1.2/spec.html) only mentions inheritance once and that in the context of how the parser functions. Therefore stating "I have YAML file with inheritance", apart from missing an article, makes no sense. Please edit your post to include what you mean by inheritance. – Anthon May 03 '17 at 10:20

2 Answers2

0

As far as I know (I also use that option to import and override) the YAML source is read and processed and then the hash elements are exposed and not linked internally. So the mechanism is copy paste override and not linking and overload.

I guess you have to modify the YAML source by opening the file and modify its content if you won't destroy your source.

Tom Freudenberg
  • 1,337
  • 12
  • 31
0

To add new section:

config = Api.get(id)
config = "#{config}\n    \n  #{section}: &#{section}\n    <<: *#{parent_section}"

To add new value:

config = Api.get(id)
matches = /^(.+)(\n  #{section}:\s*&#{section}\s*\n    )(<<:[^\n]+)?(.*)$/m.match(config)
config = "#{matches[1]}#{matches[2]}#{matches[3]}\n    #{key}: #{value}#{matches[4]}\n"
Johnathan Kanarek
  • 834
  • 1
  • 10
  • 16