Updating a YAML file in Ruby

My class:

class Mycfg @@options = {} def init @@options = YAML.load_file(Dir.pwd + PATH) end def set(key, val) @@options[key] = val end def get(key) @@options[key] end def save end end 

Using this class:

 oj = Mycfg.new oj.init if oj.get 'name' == 'tom' oj.set 'changed', Data.now end oj.save 

YAML file:

 name : tom pawd : 123456 version : 0.0.1 created : 2011-10-24 changed : 2011-10-24 

How to finish the save method to update the YAML file if something has changed?

+7
source share
1 answer

This is one liner.

w+ truncates the file to 0-length and writes as if it were a new file.

options_hash - current value @@options .

To get the full hash, you need getter / accessor. If you included @@options an instance variable instead of a class variable, you could just make attr_accessor :options and then get it with oj.options .

 File.open(Dir.pwd + PATH, 'w+') {|f| f.write(options_hash.to_yaml) } 
+11
source

All Articles