Woo hoo! thanks much. I could not find the info about
const_get(name).
Works like a champ!
If all you agents inherit from one base-class, you can use the
#inherited method of the base class to automatically initialize the
factory.
If you want to ‘delete’ the old definition of the class, you can use
Class.new (you will get warnings about constant redefinitions). This was
in a different thread a couple of days ago. Put this in the top of each
DerivedAgent definition.
So the script:
class Agent
@@factory = {}
def Agent.inherited(newAgent)
@@factory[newAgent.name] = newAgent
end
def Agent.get_agent(agent_name)
@@factory[agent_name].new
end
end
class AlphaAgent < Agent; end
class BetaAgent < Agent
def foo
‘beta foo’
end
def bar
‘bar’
end
end
puts Agent.get_agent(‘AlphaAgent’).class
puts Agent.get_agent(‘BetaAgent’).foo
simulate reloading the beta agent file:
BetaAgent = Class.new
class BetaAgent < Agent
def foo
‘new beta foo’
end
end
puts Agent.get_agent(‘BetaAgent’).foo
puts Agent.get_agent(‘BetaAgent’).bar
Produces:
ruby inherited.rb
AlphaAgent
beta foo
new beta foo
inherited.rb:27: warning: already initialized constant BetaAgent
inherited.rb:28: warning: already initialized constant BetaAgent
inherited.rb:35: undefined method `bar’ for #BetaAgent:0x27863b8
(NoMethodError)