others - ruby Psych YAML解析(包括注释)

是否可以用现有库解析注释,或者自己完成解析注释是唯一方法吗?

时间:

也可以这样做,这将改变key-value,并保留注释。


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



你可以在较低级别上迭代这些节点,以便在发出。 另外,你可以看到syck引擎是否提供你要查找的结果。


def yaml_conf_edit(fn, &block)


 conf = File.open(fn) {|f| YAML.load(f.read)}



 before = Tempfile.new('before')


 before.write(conf.to_yaml)


 before.close



 yield conf



 after = Tempfile.new('after')


 after.write(conf.to_yaml)


 after.close



 `merge #{fn} #{before.path} #{after.path}`


 before.unlink; after.unlink



 conf


end



你可以用在:


yaml_conf_edit('conf/database.yml') do |conf| 


 conf['development']['database'] = db_timestamped


end



...