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?
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) }
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