2011-04-29 50 views
5
class MyParent 
    def self.foo 
    if this_method_was_called_internally? 
     puts "yay" 
    else 
     puts "boo" 
    end 
    end 
end 

class MyLibrary < MyParent 
    foo # yay 
end 

MyLibrary.foo # boo 

這可能嗎?尋找類方法是外部還是內部調用

+0

檢查堆棧 - 有什麼搬弄是非在那裏?否則,我覺得你運氣不好。 – 2011-04-29 19:16:13

回答

2

簡單的答案是否定的。你可以用caller但是玩,它使您可以訪問調用堆棧,很像一個例外回溯:

def this_method_was_called_internally? 
    caller[1].include?(...) 
end 

caller[1]將是以前的調用,即方法調用this_method...

這是非常的hackish ,並且您從caller獲得的信息可能不夠。

請不要使用這個以外的其他實驗。

2

如果你能負擔得起自己的代碼稍加修改:

class MyParent 
    def self.foo(scope) 
    if scope == self 
     puts "yay" 
    else 
     puts "boo" 
    end 
    end 
end 

class MyLibrary < MyParent 
    foo(self) # yay 
end 

MyLibrary.foo(self) # boo 
相關問題