Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a YAML file in Ruby

Tags:

ruby

yaml

My class is:

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 I finish the method save to update the YAML file if something has changed?

like image 647
coolesting Avatar asked Oct 24 '11 03:10

coolesting


1 Answers

It's a one liner.

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

options_hash is current value of @@options.

You will need a getter/accessor to retrieve the full hash. If you made @@options an instance variable instead of a class variable you could simply do a attr_accessor :options and then retrieve it with oj.options.

File.open(Dir.pwd + PATH, 'w+') {|f| f.write(options_hash.to_yaml) }
like image 169
Erik Hinton Avatar answered Oct 17 '22 04:10

Erik Hinton