模块如何覆盖包含它的类的父类中的方法?

问题描述:

我想写的是覆盖在类的实例方法它被包含在一个模块模块如何覆盖包含它的类的父类中的方法?

这不起作用:

require 'active_support' 

class Foo 
    def bar 
    "bar" 
    end 
end 

module NewFoo 
    extend ActiveSupport::Concern 

    included do 
    alias __bar__ bar 
    end 

    def bar 
    "new " + __bar__ 
    end 
end 

class Baz < Foo 
    include NewFoo 
end 

我的期望是,Baz.new.bar.should eql "new bar"而是我得到一个undefined local variable or method '__bar__'错误。

我已经尝试过上述的变体,包括通过def self.include(base)...的旧方法无济于事。

任何指针?

有这家名为继承伟大的新发明:

module NewFoo 
    def bar 
    'new ' + super 
    end 
end 

或者更惯用

"new #{super}" 
+0

卫生署。我们一直在盯着我们的屏幕太久。日Thnx。 – 2010-11-11 17:54:36

+0

@hakanensari:我知道这种感觉。我曾经花了整整一个上午的时间来研究一些复杂的循环逻辑,试图找出最优雅的方式来做一个'inject',它为除了最后一个元素以外的每个元素都做同样的事情。然后,一位朋友看到了代码的一瞥,并说:“你*知道这只是'Array#join',对吧?” – 2010-11-11 18:58:10