0

I am trying to implement the inherited method for ActionController::Base class. My purpose is to call methods on classes that inherit from ActionController::Base like ApplicationController to make them include certain modules. At the momement my Code looks like this:

module MyModule
 def inherited(child)
 end
 def my_test_method()
 end
end
ActionController::Base.send(:extend, MyModule)

ActionController::Base.methods.include? 'my_test_method'
=> true
ActionController::Base.methods.include? 'inherited'
=> false

The code is called out of an init file of a plugin.

1 Answers1

0

inherited is a class method of Class. It can be overwritten directly to add behavior when a child class is defined. I don't see how you can do this by extending a module, but this should achieve the same result:

class ActionController::Base
  def self.inherited(child)
    puts "child created: #{child}"
  end
end

class ChildClass < ActionController::Base
end

and you will get the output:

child created: ChildClass
L0ne
  • 470
  • 3
  • 10
  • Hello LOne, as far as i know you can add classmethod to a class be extending it with a module. According to my example in the case of 'my_test_method' it works. But why doesn't it work with the inherited method? I've tried it on other classes like ActiveRecord::Base and it worked. – Alfred Schnitzler Jul 06 '12 at 11:22
  • I don't know why overwriting would work and extending doesn't. – L0ne Jul 07 '12 at 18:14