2012-07-04 76 views
0

我正在嘗試爲ActionController :: Base類實現繼承的方法。我的目的是調用繼承自ActionController :: Base的類的方法,如ApplicationController以使它們包含特定的模塊。 在momement我的代碼看起來是這樣的:是否有可能在Rails中定義ActionController :: Base類的繼承的鉤子2.3.11

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 

的代碼叫了一個插件的初始化文件。

回答

0

繼承是Class的一個類方法。在定義子類時,可以直接覆蓋它以添加行爲。我看不出你如何能做到這一點通過擴展模塊,但這應該得到相同的結果:

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

class ChildClass < ActionController::Base 
end 

,你會得到輸出:

child created: ChildClass 
+0

你好孤獨,據我知道你可以將classmethod添加到類中,並通過模塊進行擴展。根據我的例子'my_test_method'它的工作原理。但爲什麼它不適用於繼承的方法?我已經嘗試過其他類像ActiveRecord :: Base和它的工作。 –

+0

我不知道爲什麼覆蓋會起作用,而延伸則不行。 – L0ne

相關問題