TheLegend TheLegend - 9 months ago 66
Ruby Question

Ruby Appending comment block to YAML file

I have a yml file that I am using to store a list of stories I have added between releases.

I am using a rake task to dynamically update the version number based off what stories I have added to this file.

It is introducing a new process, so I created the following comment block this will help anyone commenting here to add stories in the right format:

# Version control file.
# Versions should be incremented as follows
# [X - major change] . [V - new feature] . [I - Bug fix / Small change]
# Update the undefined block with a one line readable description of what your story was about. example:
# undefined:
# stories:
# - "I - fixed spelling mistake"
# - "V - added import functionality"
# - "X - rebuilt the main dashboard"

The issue is after my rake task is done the job the file loses the comment block.

I pretty much load the YAML
versions = YAML.load_file( 'doc/release.yml' )
and then once the logic is finished I"doc/release.yml", 'w') { |f| YAML.dump(versions, f) }

is the new updated hash. However, this removes the comment block to the file.

Other solutions I have found just modify existing lines.

Is there a way to open the file and adding the above without messing up the YAML beneath. Any help will be much appreciated.

Answer Source

That the comments are lost with a dump is unfortunatly normal. You have two options:

  1. convert your versions hash to yaml { :a => 'b'}.to_yaml, add the comments and with File.write do the dump yourself, you could overwrite the normal .dump method in YAML this way
  2. assign the comments to some dummy value at the end of your yaml file so that they are read into versions and saved also.