Twitter Updates

Thursday 19 March 2009

Rubys update method

In my last attempt at a config system for ruby GUI apps I wanted to define default values for the preference options, so that if it gets expanded with new values it does not break when used with old config files.

I tried something like:
def loadConfig(configFile)
config = {}
config[:raw_conf_folder_loc] = "1"
config[:drv_conf_folder_loc] = "2"
if File.exist?(configFile)
config = open(configFile) {|f| YAML.load(f) }
end
end


This creates a config object (an array of hashes) and assign some values. Then if the config file exists move the pointer to a new object loaded from file, which then leaves the old config object to be picked up by the garbage collector. We are only left with the options in the file defined any defaults set will readback as nil.

To get around this problem I did the following:
def loadConfig(configFile)
if File.exist?(configFile)
config.update(open(configFile) {|f| YAML.load(f) })
end
#do this to set parameters that might be missing from the yaml file
if config[:raw_conf_folder_loc].nil?
config[:raw_conf_folder_loc] = "1"
end
if config[:drv_conf_folder_loc].nil?
config[:drv_conf_folder_loc] = "2"
end
return config
end

But this is an extra 3 lines per option and looks ugly.
Today I discovered a better way of doing this using the update() method.

def loadConfig(configFile)
config = {}
config[:raw_conf_folder_loc] = "1"
config[:drv_conf_folder_loc] = "2"
if File.exist?(configFile)
config.update(open(configFile) {|f| YAML.load(f) })
end
return config
end


Just like the first version but using update() instead of =, this replaces the default values that have been assigned inside the file. Full example ruby_yaml_config.rb

No comments: