From: "Nigel S.Ball" Date: 2001-10-22T11:15:55+09:00 Subject: [ruby-talk:22928] Configuration class I would like some thoughts on a question that I am trying to resolve. I have an application which is longrunning but needs to create a separate environment to eal with different states. This means that I really don't want globals and global constants apart from those which apply to all states. I also hate typing and want to be able to create the environments for each state easily. Ultimately I want to be able to load the config from a file. Starting from here $GLOBALCONSTANT = 'GLOBALCONSTANTVALUE' $globalhash = {"gh1"=>"gv1", "gh2"=>"gv2"} I have thought of the following 1. Create a Hash containing all the constants gv = {'GLOBALCONSTANT '=> 'GLOBALCONSTANTVALUE', 'globalhash' => {"gh1"=>"gv1", "gh2"=>"gv2"} } This is admittedly simple but, to me at least, is not very pretty. To access a value we have gv['GLOBALCONSTANT'] 2. Convert the Hash from thought 1 into a class (lifted from cgi.rb) class Config def initialize(hash={}) @hash = hash hash.each {|key, val| eval( <<-END ) def #{key.downcase} "#{val}" end END } end end cfg = Config.new(gv) This is somwhat more elegant as variables are accessed by cfg.globalconstant However, as it stands it can only be used for strings. Can anyone tell me how to deal with other objects? 3 Use a Struct to hold the values Config = Struct.new("Config", :globalconstant, :globalhash) cfg = Config.new('GLOBALCONSTANTVALUE', {"gh1"=>"gv1", "gh2"=>"gv2"}) This seems to have the advantages of 2 but suffers from the need to set the names of the elements and their values separately. The values are, in fact set by position, very ugly IMHO. I guess what I would really like is a class which when passed a hash returns the equivalent Struct with the values set accordingly. Any thoughts or suggestions would be appreciated. -- Nigel Ball