2009-10-10 128 views
29

也許我只是沒有使用Ruby的正確術語(如果我請更正我),但Google在這一方面沒有幫助我。從子類中的重載方法調用基類方法

我有一個類(稱爲OrderController),它擴展了另一個類(稱之爲BaseStoreController)。在BaseStoreController中,我定義了一個用於整個我的網站的before_filter,除了我的OrderController外,還有一小部分。在這種特殊情況下,我需要定義一個自定義的before_filter,它需要做一些額外的邏輯,然後調用我的BaseStoreController中定義的before_filter

我不知道的是如何做到這一點。

這裏是我嘗試過,但現在看來,「超級」的關鍵字是不是我期待它是:

class BaseStoreController < ActionController::Base 
    before_filter :authorize 

    protected 
     def authorize 
      #common authroization logic here 
     end 
end 

class OrderController < BaseStoreController 
    before_filter :authorize 

    protected 
     def authorize 
      #additional authroization logic here 
      super.authorize 
     end 
end 

最終結果我的代碼是OrderController中的授權方法失敗,出現以下錯誤:

 
You have a nil object when you didn't expect it! 
The error occurred while evaluating nil.authorize 

回答

56

您是否嘗試過調用基類的「authorize」方法只用「super」而不是「super.authorize」?

+2

哇! 我想我的經驗與其他語言在這一個傷害我...我期望超級是對基類的引用...不是對我隱藏的基類方法的引用。 工作就像一個魅力,謝謝! – 2009-10-10 04:52:08

+3

在Ruby中,'super'是對方法的繼承版本的調用,因此您在返回的任何內容(在本例中爲'nil')上調用'authorize'。 – 2009-10-10 13:10:33

+0

如何實際引用基類? – Shayne 2016-09-06 02:46:10