s12chung
s12chung

Reputation: 1768

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?

Upvotes: 14

Views: 2996

Answers (1)

kristenmills
kristenmills

Reputation: 1287

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

Upvotes: 17

Related Questions