簡體   English   中英

基於BasicObject的Ruby類無法訪問其他模塊中的代碼

[英]Ruby class based on BasicObject can't access code in other module

我正在使用method_missing來為詞匯表中的常量常量定義一個類。 為了有效,我需要詞匯表類從BasicObject繼承,否則,沒有標准的對象方法可用作詞匯表項(因為該方法沒有丟失:)。 但是,當我從BasicObject繼承時,我發現無法在另一個模塊中調用實用程序方法。 以下代碼以簡潔形式說明了此問題:

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添加些什么,以便在嘗試調用helper模塊時不會產生統一的常量錯誤?

如果您像這樣在V2更改方法,則該方法將起作用,以便名稱解析在全局范圍內開始。

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

我在文檔中為您查找了它:

BasicObject不包含內核(用於puts之類的方法),並且BasicObject在標准庫的命名空間之外,因此,如果不使用完整的類路徑,將找不到常見的類。 ...在Ruby標准庫中訪問類和模塊可以在BasicObject子類中獲得,方法是從根目錄中引用所需的常量,例如:: File或:: Enumerator。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM