Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Psych YAML parsing including comments

Tags:

ruby

yaml

psych

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?

like image 949
hjuskewycz Avatar asked Jul 31 '12 06:07

hjuskewycz


2 Answers

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
like image 115
Mrigesh Priyadarshi Avatar answered Nov 18 '22 01:11

Mrigesh Priyadarshi


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.

like image 1
Bjoern Rennhak Avatar answered Nov 18 '22 01:11

Bjoern Rennhak