Twitter Updates

Tuesday, 17 March 2009

Lightweight preference system for ruby

UPDATE:
I have replace this method with a yaml method

Original Post:
When using GUI applications it is often nice for them top remember some of the settings, here is some snippets of a preferences system:

Near start of ruby app/script
----
   outputFile = ".photoflow/.photoflowrc"

#Define before opening so new variables are definde empty.
# If undefiened never get added to the config file,
# which is a pain for manual edits.
@raw_conf_folder_loc = ""
@drv_conf_folder_loc = ""

#Loaded Prefs from file
if File.exist?(outputFile)
configfile = File.new(outputFile, "r")
while (line = configfile.gets)
eval("#{line}")
end
configfile.close
end

----

When any of the user setting are changed call 'createConfig'
----
 def createConfig(outputFile, raw_conf_folder_loc, drv_conf_folder_loc)
FileUtils.mkdir_p (".photoflow")
## Delete output File if It exists
if File.exists?(outputFile)
File.delete(outputFile)
end

outputFileHandler = File.new(outputFile, File::CREAT|File::WRONLY)
outputFileHandler.puts("\@raw_conf_folder_loc = \"" + raw_conf_folder_loc + "\"")
outputFileHandler.puts("\@drv_conf_folder_loc = \"" + drv_conf_folder_loc + "\"")
return
end

----

I have some problem with the scope of the variables, ideally I would not need to pass them as arguments to the function.

NB: Ruby functions are contained in def's, ie def SomeFunction end

No comments: