Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load and save a YAML file without losing quotes or comments in Ruby

Tags:

ruby

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?

like image 473
Alex Harvey Avatar asked Aug 27 '16 15:08

Alex Harvey


People also ask

Does YAML file need quotes?

For most scalars you don't need any quotes at all, but if you need to define some piece of data which contains characters that could be mistaken with YAML syntax you need to quote it in either double " or single ' quotes for the YAML file to stay valid.

How do you save in YAML?

Create a file from the YAML URL Now click on these YAML samples. Once this link is open, use save as functionality of the browser and save. It will generate YAML file and save it on your device.

How do I use special characters in YAML?

Use quotes in YAML if your value includes special characters. For example, these special characters may require quotes: {, }, [, ], ,, &, :, *, #, ?, |. -, <. >, =, !, %, @, \. It is not necessary to use quotes when a single special character is surrounded by spaces, for example, * with spaces on both sides.


1 Answers

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.

like image 149
Alex Harvey Avatar answered Sep 23 '22 12:09

Alex Harvey