是否可以在Rails 2.3.11中为ActionController :: Base类定义继承的钩子

时间:2012-07-04 07:29:29

标签: plugins module ruby-on-rails-2 inherited development-mode

我正在尝试为ActionController :: Base类实现继承的方法。我的目的是调用继承自ActionController :: Base的类的方法,如ApplicationController,以使它们包含某些模块。 在我的代码中,我的代码看起来像这样:

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

代码是从插件的init文件中调用的。

1 个答案:

答案 0 :(得分:0)

继承是Class的类方法。在定义子类时,可以直接覆盖它以添加行为。我不知道如何通过扩展模块来实现这一点,但这应该会达到相同的结果:

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

class ChildClass < ActionController::Base
end

您将获得输出:

child created: ChildClass