Saturday, March 14, 2009

Weekly Source Code: Ruby Setting Utility Class

Its a general task to store application settings so I wrote my own for the Ruby programming language

How to use:

Save the SettingUtil.rb file so that your application code can find it.

Add:

require 'SettingsUtil'
include SettingUtil

Save Example:

require 'SettingsUtil'
include SettingUtil

setting = Settings.new # create the settings object
setting.values = {"jabber_notifyme" => "true", "jabber_jid" => "lenniedg@gmail.com", "jabber_password" => "", "jabber_to" => "lenniedg@gmail.com"}
setting.save
puts setting.jabber_to

to save you need to set the values accessor which is a hashset then call the save method.

Load Example:

require 'SettingsUtil'
include SettingUtil

setting = Settings.new
puts setting.values["jabber_to"]

when creating a new object of Settings (remember its in the SettingUtil module) it will load the previous saved settings else you can just call load method directly.

Note:

There are 2x ways to get the settings value:

puts setting.jabber_to

OR

puts setting.values["jabber_to"]

in both cases it reads the setting of "jabber_to" from the values hashset.

If it can't find the setting the first option will return "none" by default where the second option will return a nil reference.

By default it save settings into a settings.config file, you might want to change that if you wish.

The source:

#
# Store application settings
# Settings get marchalled to a file and then loaded, you can refer to settings
# by getting them from the values accessor directly or calling a method
#
# Author: Lennie De Villiers
# Created: 12/03/2009

module SettingUtil
SettingsFileName = "settings.conf" # constant with the file name
attr_accessor :values
class Settings
def initialize()
values = {}
load()
end

def load()
if File.exists?(SettingsFileName)
f = open(SettingsFileName)
temp = Marshal.load(f)
self.values = temp.values
end
end

def save()
open(SettingsFileName, "w") { |f| Marshal.dump(self, f) }
end

def method_missing(method_name, *args)
if values != nil && values.key?(method_name.to_s)
return values[method_name.to_s]
else
return "none"
end
end
end
end

No comments: