2012-06-13 47 views
0

我正在使用method_missing爲詞彙表中的名稱間距常量定義類。爲了有效,我需要從BasicObject繼承詞彙類,否則沒有標準的對象方法可用作詞彙表術語(因爲方法不會丟失:)。但是,當我從BasicObject繼承時,我發現我無法在另一個模塊中調用實用程序方法。下面的代碼說明了壓縮形式的問題:基於BasicObject的Ruby類無法訪問其他模塊中的代碼

module Foo 
    class Bar 
    def self.fubar(s) 
     "#{s} has been fubar'd" 
    end 
    end 
end 

class V1 
    def self.method_missing(name) 
    Foo::Bar.fubar("#{name} in v1") 
    end 
end 

class V2 < BasicObject 
    def self.method_missing(name) 
    Foo::Bar.fubar("#{name} in v2") 
    end 
end 

# this works 
puts V1.xyz 
# => xyz in v1 has been fubar'd 

# this doesn't 
puts V2.xyz 
# => NameError: uninitialized constant V2::Foo 

我將需要添加到V2所以,當我嘗試打電話給助手模塊也不會產生一個未初始化常數錯誤?

回答

3

如果你像這樣改變V2中的方法,它會起作用,因此名稱解析在全局範圍內開始。

def self.method_missing(name) 
    ::Foo::Bar.fubar("#{name} in v2") 
end 

我看着它在the documentation for you

BasicObject不包括內核(像放方法)和 BasicObject是標準庫的命名空間之外,以便 常見的類不會被沒有使用完整的課程路徑找到。 ... 通過從類似於:: File或:: Enumerator的根目錄中引用期望的常量 ,從Ruby標準庫訪問類和模塊可以是在BasicObject子類中獲得的 。