Is it possible to code something that can tell me when a Ruby class is defined?
Asked
Active
Viewed 91 times
0
-
Could you please tell us what you actually want from us? – Arup Rakshit Feb 23 '13 at 15:37
1 Answers
2
Yes!
class Object
def self.inherited(base)
puts "#{base} inherited from object"
end
end
class Animal
end
class Cat < Animal
end
Running the above code prints the following:
Animal inherited from object
Cat inherited from object
Basically, the self.inherited
callback is triggered whenever a class is defined that inherits from the class it is defined on. Put it on Object
and that's any class! (Although there may be some special case exceptions I can't think of just now).
I should probably add the disclaimer that, while it is possible to do this (because of just how awesome Ruby is as a language), whether it is advisable to do this, especially in code destined for production use, I'm not so sure. Well, actually, I am sure. It would be a bad idea.

Russell
- 12,261
- 4
- 52
- 75