无法在Ruby on Rails中使用猴子修补覆盖类方法

时间:2015-07-14 14:17:06

标签: ruby-on-rails ruby activerecord monkeypatching

所以我想在reflect_on_association覆盖类方法 ActiveRecord::Reflection。这是原始文件的链接: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仍然没有运气。

任何人都知道如何做到这一点?非常感谢你!

1 个答案:

答案 0 :(得分:0)

在五月工作!

确保使用reflect_on_association传递参数。

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