Writing YAML files in Ruby: lack of pretty printing formatting options

What do you think about it ?

Ciao Giorgio,

Most YAML libraries I’ve worked with don’t preserve formatting or
comments. Some quick research turns up only one that does—and it’s for
Python (ruamel.yaml). In my experience, YAML is great for
human-friendly, machine-readable configuration files and not much else.
It loses its allure the second you bring machine-writeability into the
picture.

In the past, when I’ve needed to programmatically update a YAML file, I
try to treat it like any other text file. That is, I’ll seek to the
line(s) I want to edit, apply a regex substitution or what have you, and
write out the updated file. If I have to do a lot of heavy lifting
within the file and it makes more sense to manipulate the data directly,
I resign myself to losing my preferred formatting, and put all of my
comments in as data, i.e. instead of this:

# This file contains the configuration for yadda yadda yadda...
# Lorem ipsum dolor sit amet, consectetur adipiscing elit.
---
- apples # red
- oranges # orange
- bananas # yellow
...

I’ll do something like this:

---
README: |
    This file contains the configuration for yadda yadda yadda...
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
...
---
- item: apples
  comments: red
- item: oranges
  comments: orange
- item: bananas
  comments: yellow
...

I feel like I’m giving this answer a lot lately, but if you really need
a YAML library for Ruby that preserves comments and formatting, it might
be fun to write! :slight_smile:

Thanks for your answer, Mike
You perfectly got the point with your example containings comments and
pretty printed data.
In facts key “comment” in my example is just to simulate a … comment
as you did in your README key example.

Probably you are right: I could made “Yet Another YAML” gem myself :slight_smile:
a bit of parsing exercise (I’m not so good in parsing programming).
And the reason I asked here is because I hope some one else already did
a better gem :slight_smile:

BTW, the “raugh” Ruby YAML implementation in 2016, seriously surprise me
a bit, because, If I well remebers, few years ago, almost every Ruby
tutorial for beginners as me, was starting with statement:
YAML everywhere!
YAML everywhere!
YAML everywhere!
(See Rails configs too, etc.)

Anyway, jokes a part: Yes, YAML is not perfect, but I’m still interested
in YAML as shareable format comprensible by both humans and both
machines :wink: Ok otherwise we have JSON, binary mixin like superb
messagepack.org and of course binary blobs data at the opposite extreme
:slight_smile:

Sure, YAML everywhere in Rails, but only for human-friendly,
machine-readable configuration. Does Rails ever write back out to YAML?

Does Rails ever write back out to YAML?

No, I agree :slight_smile:
But this is not a good reason
to do not write YAML files
(I’m Rails oppositor, joking)