2013-07-18 20 views
2

我有很多的其方法的通用模式的子類:如何捕獲對super的引用並將其傳遞?

if some_condition 
    (real code goes here) 
else 
    super 
end 

理想我想封裝它是這樣的:

def if_some_condition 
    if some_condition 
    yield 
    else 
    (calling method's super) 
    end 
end 

有什麼辦法,我捕捉到調用方法的super以便我可以在if_some_conditionelse分支中調用它?

(暗示使用另一亞類中的之前,請注意some_condition可以通過在該類對象的生存期經常改變)


編輯:

一種可能的解決方案是:

def if_some_condition(&b) 
    if some_condition 
    yield 
    else 
    b.send(:binding).eval('super') 
    end 
end 

但是,如果可能,我寧願避免使用eval

回答

0

我想你永遠不應該從外部類調用super ...也許你可以添加一個布爾參數「超級」,當「超級」是真的,你調用超級方法

你可以看到結果這裏:http://repl.it/KOd

class My_base_class 
    def methode_one(argument={}) 
    puts "yabadabadou" 
    end 
end 

class My_sub_Class < My_base_class 
    def methode_one(argument={}) 
    if(argument[:super]) 
     puts "taratata" 
    else 
     super 
    end 
    end 
end 


def if_some_condition(b) 
    if 1==1 
    b.methode_one({:super=>false}) 
    else 
    b.methode_one({:super=>true}) 
    end 
end 

def if_some_other_condition(b) 
    if 1==0 
    b.methode_one({:super=>false}) 
    else 
    b.methode_one({:super=>true}) 
    end 
end 
相關問題