8

I have a requirement to programmatically edit YAML files in Ruby, and I need to also retain the enclosing quote characters unfortunately. Being able to retain the comments too would be a bonus.

That is to say if I have a file:

---
foo: 'bar'

or

---
foo: "bar"

My script must not write it back as:

---
foo: bar

And as mentioned, ideally I need to preserve comments too.

Without going down the path of just treating the whole file as a stream of text, is there any convenient way to solve one or both of these problems?

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97
  • Couldn't you just follow the instructions [here](http://stackoverflow.com/questions/14532959/how-do-you-save-values-into-a-yaml-file) but with a string instead of an integer? – Polyov Aug 27 '16 at 15:19
  • you'll need your own parser if one doesn't exist in ruby for ignoring the comment text. As for the file removing the quotes, that's per yaml spec, a string doesn't have to be enclosed but is usually enclosed when it will make the string less ambiguous (e.g. characters like `[`,`]`,`,`,`"` in it) – Rogue Aug 27 '16 at 15:19

1 Answers1

5

At the time of writing, it appears this is impossible to implement in Ruby, unless you are prepared to write your own YAML parser. I investigated other languages including Perl and Python, and found there is a Python Library called Ruamel that can do this - or more accurately, it will be able to do this when all of its bugs are fixed! So I have re-written my application in Python. See also this answer here.

Community
  • 1
  • 1
Alex Harvey
  • 14,494
  • 5
  • 61
  • 97