簡體   English   中英

無法在Ruby on Rails中用猴子補丁覆蓋類方法

[英]Can't override class method with monkey patching in Ruby on Rails

所以我試圖覆蓋 ActiveRecord::Reflection 的類方法 reflect_on_association 這是原始文件的鏈接: https : //github.com/rails/rails/blob/master/activerecord/lib/active_record/reflection.rb

該方法在第106行中定義。

到目前為止,這是我的嘗試:

1。

ActiveRecord::Reflection::ClassMethods.module_eval do
  # A test method
  def say_hello
    puts 'hello'
  end

  # I want to override the original method with this one
  def reflect_on_association(association)
    puts 'overridden!'
    # < Implementation goes here >
  end
end

2。

module ActiveRecord::Reflection::ClassMethods
  # A test method
  def say_hello
    puts 'hello'
  end

  # I want to override the original method with this one
  def reflect_on_association(association)
    puts 'overridden!'
    # < Implementation goes here >
  end
end

say_hello方法適用於這兩種情況下(例如,當我打電話Person.say_hello ),但仍然沒有運氣reflect_on_association

有人對我該怎么做有任何想法嗎? 非常感謝你!

在可能的情況下工作!

確保您使用reflect_on_association傳遞參數。

1.9.3-p551 :514 > Person.reflect_on_association(state)
overridden!
=> nil 

暫無
暫無

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

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