2013-01-18 42 views
1

可能重复:
When monkey patching a method, can you call the overridden method from the new implementation?通过覆盖的方法添加功能,但还是把原来的方法

所以我想简单地通过重写它的一些条件检查添加的方法,但后来我想要调用原始方法。一个人如何做到这一点在红宝石?

即。

方法存在

def fakeMethod(cmd) 
    puts "#{cmd}" 
end 

,我想补充

if (cmd) == "bla" 
    puts "caught cmd" 
else 
    fakeMethod(cmd) 
end 

任何想法?

+0

这是[当猴子打补丁的方法,你可以在新的实现中调用重写的方法]的副本(http://stackoverflow.com/a/44712​​02/2988)。 –

回答

7
alias :old_fake_method :fake_method 
def fake_method(cmd) 
    if (cmd) == "bla" 
    puts "caught cmd" 
    else 
    old_fake_method(cmd) 
    end 
end 
0

这里有alias_method_chainalias _method在ruby中。

(alias_method_chain不是红宝石,但在的ActiveSupport :: CoreExtensions,所以你minght需要要求,如果这不是一个Rails应用程序)

1

为什么不使用继承。这是一个经典的例子重写方法是增加额外的逻辑:

class Foo 
    def foo(cmd) 
    puts cmd 
    end 
end 

class Bar < Foo 
    def foo(cmd) 
    if cmd == "hello" 
     puts "They want to say hello!" 
    else 
     super 
    end 
    end 
end 

Foo.new.foo("bar") # => prints "bar" 
Bar.new.foo("hello") # => prints "They want to say hello" 

当然,如果你有机会来实例化一个子类的实例此解决方案仅适用。

+1

+1提到的 – christianblais