从子类中的重载方法调用基类方法

Jas*_*orn 37 ruby ruby-on-rails

也许我只是没有使用Ruby的正确术语(如果我请你纠正我),但谷歌并没有帮助我.

我所拥有的是一个类(称为OrderController),它扩展了另一个类(称之为BaseStoreController).在BaseStoreController中,我已经定义了一个before_filter在我的网站中使用的,除了我的OrderController以外的一小部分.在这种非常特殊的情况下,我需要定义一个before_filter需要做一些额外逻辑的自定义,然后调用before_filter我的BaseStoreController中定义的.

我不知道的是如何做到这一点.

这是我尝试过的,但似乎'super'关键字不是我所期望的那样:

class BaseStoreController < ActionController::Base
    before_filter :authorize

    protected
        def authorize
            #common authroization logic here
        end
 end
Run Code Online (Sandbox Code Playgroud)

class OrderController < BaseStoreController
    before_filter :authorize

    protected
        def authorize
            #additional authroization logic here
            super.authorize
        end
 end
Run Code Online (Sandbox Code Playgroud)

我的代码的最终结果是OrderController中的authorize方法失败,出现以下错误:

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

pyt*_*ick 63

您是否尝试authorize使用" super"而不是" "来调用基类的" "方法super.authorize

  • 哇!我想我在使用其他语言时遇到的经验让我受到了损害...我希望super能够成为对基类的引用...而不是对我隐藏的基类方法的引用.这就像一个魅力,谢谢! (4认同)
  • 在Ruby中,`super`是对方法的继承版本的调用,所以你在返回的任何内容上调用`authorize` - 在这种情况下,``nil`. (4认同)
  • 如何实际引用基类? (2认同)