Reputation: 45
Is it possible to code something that can tell me when a Ruby class is defined?
Upvotes: 0
Views: 95
Reputation: 12439
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.
Upvotes: 2