从子类中的重载方法调用基类方法
问题描述:
也许我只是没有使用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
答
您是否尝试过调用基类的“authorize
”方法只用“super
”而不是“super.authorize
”?
哇! 我想我的经验与其他语言在这一个伤害我...我期望超级是对基类的引用...不是对我隐藏的基类方法的引用。 工作就像一个魅力,谢谢! – 2009-10-10 04:52:08
在Ruby中,'super'是对方法的继承版本的调用,因此您在返回的任何内容(在本例中为'nil')上调用'authorize'。 – 2009-10-10 13:10:33
如何实际引用基类? – Shayne 2016-09-06 02:46:10