From: gabriele renzi Date: 2004-04-01T02:44:21+09:00 Subject: Re: script loading question il Wed, 31 Mar 2004 17:24:54 GMT, Greg Brondo ha scritto:: >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| > agent = File.basename(agent) > if agent =~ /^((\w+)Agent)\.rb/ > require $1 > $agentFactory[$2.downcase] = $1 > end > } >end I suppose this is reasonable, even if I'd simplify it using an agent/ directory, and I would it like this: def loadAgents Dir['Agents/*.rb'].each do |agent| load agent end def agent_create(name) Object::const_get(name).new end or at least I'd use a constant AgentFactory instead of an ugly dollar-var. >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, require is a one time thing, and load works as expected: >> load 'agen.rb' => true >> Agent.new => # >> class Agent >> def initialize >> @b=2 >> end >> end => nil >> Agent.new => # >> load 'agen.rb' => true >> Agent.new => #