开发者

Delegating to the base class implementation

How can I delegate the invocations within a baseclass to the base class implementation rather than the inherited class implementation? For example:

class A 

 def foo
  p "hello"
 end

 def bar
  foo 
 en开发者_JAVA百科d

end 

class B < A

  def foo
    p "world"
  end  

end


A.new.bar
# prints "hello"

B.new.foo
# prints "world"


B.new.bar
# prints "world"
# the function should print "hello" instead

In the example above, what is the most elegant way to print hello when the foo method is invoked within the base class by bar method?


Based on my understanding of the ruby method lookup algorithm I do not believe that it is possible to achieve what you are trying to do without using different method names or without over-ridding the bar method in the subclass also.

The problem is that the "self" that receives the foo message when called by the bar method in class A will always be the instance of class B (when called from an instance of class B). Since class B's own foo method will always be found first by ruby's method lookup algorithm there is no way call class A's original foo method (class B is after all overriding the inherited foo method from class A).

A not so elegant solution would be to use "around aliases" as shown below but it does require over-riding the bar method also:

class B < A
  alias :old_foo :foo

  def foo
    p "world"
  end

  def bar
    old_foo
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜