Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Execute code for every subclass

Given a parent class is there a way to insert code for every subclass on load? ie.

Given: ParentClass, how do I insert code like so:

class ChildClass < ParentClass
   execute_function

   ...
end

for all child classes of ParentClass?

like image 626
s12chung Avatar asked Aug 22 '13 20:08

s12chung


1 Answers

In the ParentClass override the inherited method

class ParentClass
   def self.inherited(subclass)
      execute_function
      super
   end
   ...
end

See: http://ruby-doc.org/core-2.0/Class.html#method-i-inherited

like image 148
kristenmills Avatar answered Oct 21 '22 14:10

kristenmills