2013-11-23 19 views
0

我想調用一個類的過程,但從它與訪問實例方法與繼承類。我覺得有些模擬代碼會更有意義:)從類方法proc訪問實例方法

class Bar 
    def self.foo &block 
    @foo ||= block 
    end 
    def foo; self.class.foo.call(); end 
    def bar; 'bar'; end 
end 

class Foo < Bar 
    foo do 
    bar 
    end 
end 

Foo.new.foo 
# NameError: undefined local variable or method `bar' for Foo:Class 

我希望能夠訪問的酒吧類bar實例方法。使用繼承類中的塊調用foo類方法的原因是DSL要求的一部分,但對於更好設計的任何建議都將不勝感激。

+2

這兩個foos很混亂。 –

+0

爲什麼'new.bar'或者使'bar'類方法不好? –

+0

@SergioTulentsev哈!對不起...我不是很有創意,我的作品代碼:) – brewster

回答

0

塊在詞彙範圍內,包括值self。在定義塊的位置,selfBarBar不響應bar。您需要在對象的上下文中評估塊(在本例中爲實例Bar而不是Bar本身)您要調用的方法。這就是instance_eval做:

class Bar 
    def self.foo(&block) @foo ||= block end 
    def foo; instance_eval(&self.class.foo) end 
    def bar; 'bar' end 
end 

class Foo < Bar; foo do bar end end 

Foo.new.foo 
# => 'bar' 

注意,所有關於instance_eval通常免責聲明適用:因爲你改變self方法和實例變量,該塊作者可能認爲可用的不會是值。

+0

完美!我實際上是在早些時候玩過instance_eval,但由於我沒有使用&符號將它轉換爲proc,所以它不起作用。但現在它是有道理的。謝謝! – brewster