Execute code on descendant class init

C

Chris Morris

I've got the following code:

class Main
@@classes = []

def Main.classes
@@classes
end
end

class Root
Main.classes << self
end

class A < Root
end

class B < Root
end

puts Main.classes.inspect


I'd like Main.classes == [Root, A, B], but currently it only is [Root].
I understand why, but was wondering if there was an elegant way to get
what I'd like to have.

I know in this example, I could simply add "Main.classes << self" to
each subclass, but, hey, that's way too much repetition for the 21st
century. :)
 
G

Gennady

I've got the following code:

class Main
@@classes = []
def Main.classes
@@classes
end
end

class Root
Main.classes << self
end

class Root
Main.classes << self
def self.inherited(sub_class)
Main.classes << sub_class
end
end

class A < Root
end

class B < Root
end

puts Main.classes.inspect


I'd like Main.classes == [Root, A, B], but currently it only is
[Root]. I understand why, but was wondering if there was an elegant
way to get what I'd like to have.

I know in this example, I could simply add "Main.classes << self" to
each subclass, but, hey, that's way too much repetition for the 21st
century. :)

Sincerely,
Gennady Bystritsky
 
R

Robert Klemme

Chris Morris said:
In my example, the subclasses descend from Root, not Main.

Then I'd define the class collection in Root and not Main. My point was
simply to put both into the same class. If you put it into Root you can
even extend the scheme so that for sub classes "inherited" is
automatically defined, in order to make this work recursively.

Regards

robert
 
C

Chris Morris

Robert said:
Then I'd define the class collection in Root and not Main. My point was
simply to put both into the same class. If you put it into Root you can
even extend the scheme so that for sub classes "inherited" is
automatically defined, in order to make this work recursively.

Ah, interesting ... I'll have to look that over (my brain is away from
the problem right now). Thx!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top