2010-04-10 20 views
3

以下是我想簡化的一段代碼,以避免在每次調用時傳遞額外的參數。實際上,我的用例是M是一個用戶庫,沒有在每個方法上定義context參數。 check是一個未由​​用戶定義的方法。如何在Ruby中檢索調用者上下文對象?

# User code 
module M 
    def do_something(context) 
    puts "Called from #{context}" 
    context.check 
    end 
    module_function :do_something 
end 

# Application code 
class Bar 
    def check 
    puts "Checking from #{self}..." 
    end 
end 

class Foo < Bar 
    def do_stuff(scope, method) 
    scope.send method, self 
    end 
end 

# Executed by user 
Foo.new.do_stuff M, :do_something 

有沒有辦法做同樣認爲,如果沒有經過self作爲輸入參數do_something方法,以便檢索check方法?

# User code 
module M 
    def do_something 
    called_from_object = ??? 
    puts "Called from #{called_from_object}" 
    called_from_object.check 
    end 
    module_function :do_something 
end 

# Application code 
class Bar 
    def check 
    puts "Checking from #{self}..." 
    end 
end 

class Foo < Bar 
    def do_stuff(scope, method) 
    scope.send methood 
    end 
end 

# Executed by user 
Foo.new.do_stuff M, :do_something 

感謝您的支持!

回答

1

不是你要求的,但如果Foo包括M那會讓你做到你在做什麼?例如

module M 
    def do_something 
    puts "I am going to use the test method from the including class" 
    test 
    end 
end 

class Foo 
    include M 
    def test 
    puts "In Foo's test method" 
    end 

    def do_stuff 
    do_something 
    end 
end 

,然後你可以這樣做:

irb(main):019:0> Foo.new.do_stuff 
I am going to use the test method from the including class 
In Foo's test method 

如果這個想法是有一個模塊提供一些通用的功能,並在一個類中的細節,那麼這是在Ruby中一個相當普遍的模式,例如Comparable模塊要求包含類實現<=>

+0

我有着類似模塊上的樣子,但我不認爲我的問題和模塊之間的鏈接...你可以去到更多的細節? – David 2010-04-11 09:30:23

+0

當模塊被固定爲一個特定模塊時(例如,在問題的原始版本中使用'M'),那麼'Foo'類可以包含'M',然後當'do_stuff'調用包含的'do_something'自己時Foo的實例。但是,如果模塊被作爲參數傳遞do_stuff(如更新示例中那樣),那麼我認爲您需要一種不同的方法。 – mikej 2010-04-11 13:09:12

+0

感謝您的反饋,我同意在特定模塊「M」的情況下。我最初的帖子是一個特定的案例,沒有反映我真正想做的事情。 – David 2010-04-11 13:45:41

5

在爲我自己的目的尋找答案時遇到了這篇文章。

沒有找到合適的代碼,所以我通過Ruby源代碼挖掘了一個擴展。我已經捆綁它作爲一個偕應該安裝沒有任何問題,只要您使用的1.9.1:

sudo的創業板安裝發件人

不會使用Ruby 1.8的工作因爲1.8具有跟蹤幀的不同模型。

http://rubygems.org/gems/sender