From: Simon Strandgaard Date: 2004-04-01T02:54:27+09:00 Subject: Re: script loading question On Wed, 31 Mar 2004 18:31:14 +0000, Greg Brondo wrote: > Greg Brondo wrote: > >> I like working in the style of Java (one class per file) for some projects >> and I've emulated it for an email/webagent app. What I'm wondering is if >> there is a *better* or *builtin* way to do this. Here is my code: >> >> def loadAgents(path) >> Dir[path + "*Agent.rb"].each { |agent| Maybe do ? Dir[File.join(path, "*Agent.rb"] >> agent = File.basename(agent) >> if agent =~ /^((\w+)Agent)\.rb/ >> require $1 >> $agentFactory[$2.downcase] = $1 >> end >> } >> end watch out about using the global variables, while doing something in the meantime (require). Who knows maybe the required file will modify $2 ? Instead I suggest doing (untested) match = agent.match /^((\w+)Agent)\.rb/ if match require match[1] $agentFactory[match[2].downcase] = match[1] end >> >> I initialize '$agentFactory' to '{}' and add 'lib/' to $: before calling >> loadAgents(). Then I can 'object = agentFactory[request].new()'. Also I >> can add agents just by writing the class in a new agent file in lib and >> restarting. >> >> I guess another question would be how can I reload 'lib/' without >> restarting? Does 'load' replace class definitions (it seems require is a >> 'one time thing')? Yes, you are correct about require. There is nothing special about load, it simply loads the file and evaluates the content. However load doesn't replace classes. Ruby has a concept named class reopening. The first time you evaluate the class its being _created_, the succeding times you evaluate the class then you will reopen the class. -- Simon Strandgaard