From: "Nigel S.Ball" Date: 2001-10-22T13:22:59+09:00 Subject: [ruby-talk:22930] Re: Configuration class As usual I have answered one of my questions myself! On Mon, 22 Oct 2001 12:15, you wrote: > 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}" replace this line with #{val.inspect} > 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? I can answer this myself now ... use value.inspect > > 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 S. Ball Enesbe Sales Pty Ltd Ph: 61 3 9909-7970 Fx: 61 3 9909-7971 Mob: 0417 341 300