簡體   English   中英

Ruby繼承和覆蓋類方法

[英]Ruby Inheritance and overwriting class method

我已經設置了兩個類,如下所示

class Parent

  def self.inherited(child)
    child.custom_class_method
  end

  def self.custom_class_method
    raise "You haven't implemented me yet!"
  end
end

class Child < Parent

  def self.custom_class_method
    "hello world"
  end
end

似乎在評估繼承Child < Parent時,它會調用self.inherited ,這反過來會提高Parentself.custom_class_method版本而不是Child的版本。 這是一個問題,因為我沒有得到預期的"hello world" ,而是出現了一個錯誤,說"You haven't implemented me yet!"

Childself.custom_class_method是否在Parentself.inherited完成評估之后才會被評估? 如果是這樣,是否有解決方法? 我不應該對 Parent 類進行raise檢查嗎?

我認為這應該澄清:

class Parent
  def self.inherited(child)
    puts "Inherited"
  end
end

class Child < Parent
  puts "Starting to define methods"
  def self.stuff; end
end

輸出清楚地表明, .inherited在打開新類時.inherited調用,而不是在關閉新類時被調用。 因此,正如您所猜測的那樣, Child.custom_class_method在您嘗試調用它時不存在-所有.inherited看到的都是空白。

(關於如何解決它……不幸的是,我不能不對您正在嘗試做的事情有更多的了解。)

模板模式/延遲初始化可能有助於解決您的問題。 該代碼假定子類之間的不同之處在於數據庫連接信息,可能只是表名或完全不同的數據庫。 父類具有用於創建和維護連接的所有代碼,而子類僅承擔提供不同之處的責任。

class Parent
  def connection
    @connection ||= make_connection
  end

  def make_connection
    puts "code for making connection to database #{database_connection_info}"
    return :the_connection
  end

  def database_connection_info
    raise "subclass responsibility"
  end
end

class Child1 < Parent
  def database_connection_info
    {host: '1'}
  end
end

class Child2 < Parent
  def database_connection_info
    {host: '2'}
  end
end

child1 = Child1.new
child1.connection  # => makes the connection with host: 1
child1.connection  # => uses existing connection

Child2.new.connection  # => makes connection with host: 2

您必須將self.inherited包裝在Thread.new

例子:

class Foo
  def self.inherited klass
    begin
      puts klass::BAZ
    rescue => error
      # Can't find and autoload module/class "BAZ".
      puts error.message
    end

    Thread.new do
      # 123
      puts klass::BAZ
    end
  end
end

class Bar < Foo
  BAZ = 123
end

暫無
暫無

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

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