Le 24 juillet 2007 à 10:02, Robert D. a écrit :
On 7/24/07, F. Senault [email protected] wrote:
Is there a trick somewhere that would allow me to trigger the inherited
method at each time the file containing the “sub-class” (e.g. Test2) is
loaded ?
As Todd pointed out already, “inheritance” will happen only once,
might it be that you have chosen a suboptimal mechanism for what
you want to achieve?
Maybe you could tell us a little bit more about that?
The full code is there :
It’s working behind the scenes in this project :
http://talisker.lacave.net/news/ngraph/
Basically, I have a Plugin class, which implements a few methods,
including at the class level.
Then, I reuse this class in a few projects, by inheriting it in a base
class. For instance, I can write :
class Tester < Plugin
plugin_must_implement :register
plugin_must_implement :getdata
plugin_load_glob “./testers/[a-zA-Z0-9].rb”
methods
end
Then, when I use Tester.load!, all the files in the specified path are
load’ed, and all the classes inheriting from Tester are registered as
plugins of that class, validated against the obligatory methods, and,
unless told otherwise, an instance of each is created and made available
and enumerable through an array. Then, I can use, for instance :
Tester.each do |t|
t.register
d = t.getdata
process the tester data
end
In the concrete case of my newsserver, I collect data to make the graphs
from different sources. So, when I have new data, instead of modifying
the main body of the grapher program, I can add a new plugin in a small
rb file (averaging 25 lines) and it’s “magically” taken into account…
I’ve already managed to reuse this class in at least four different
projects, and I kind of like the concept…
Now, in the event of a long running process, I would like to “hotplug”
the plugins, and, so, be able to simply reload everything. My problem
is that I don’t see how I can find the classes contained in a file I
just loaded without playing with inherited / Object.constants.
My current working idea is this one :
#! /usr/local/bin/ruby
#module Toto
class Test
class <<self
attr_accessor :loaded_classes
def do_load
@loaded_classes ||= {}
[ “test2.rb”, “test3.rb” ].each do |f|
o = Object.constants
load f
( Object.constants - o ).each do |c|
t = Object.const_get(c)
if t.is_a? Class then
if t.superclass == Test then
@loaded_classes[f] ||= []
@loaded_classes[f] << t
end
end
end
end
end
end
end
Test.do_load
p Test.loaded_classes
Test.do_load
p Test.loaded_classes
Needless to say, I still believe inherited was a bit simpler…
(And it doesn’t cope with classes being suppressed.)
Fred