According to http://yaml.org/spec/current.html#id2509980 comments in YAML files are a presentational detail and must not be in the serialization/representation graph ( http://yaml.org/spec/current.html#representation/). It looks like Psych is parsing according to spec and loses the comments which means that it is not possible to parse a YAML file and serialize it again exactly the same way when the file contains comments. Which in my opinion is very strange because comments do matter in such file (e.g. configs).
Does anyone know if it possible to parse comments with an existing library or is the only way to go to do it all by myself?
We can do some thing like this also, which would change the key value and also keep the comments.
require 'yaml'
thing = YAML.load_file('/opt/database.yml')
hostname = thing["common"]["host_name"]
appname = thing["common"]["app_name"]
motdobj = IO.readlines('/opt/database.yml')
motdobj = motdobj.map {|s| s.gsub(hostname, "mrigesh")}
motdobj = motdobj.map {|s| s.gsub(appname, "abc")}
File.open('/opt/database.yml', "w" ) do | file1 |
file1.puts motdobj
file1.close
end
You could iterate over the nodes on a lower level keeping the comments when emitting. Also, you could see if syck engine gives you the result you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With