2013-01-18 87 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