猴子用 Mongoid 修补 Rails 中的数据库模型 class 会导致奇怪的行为

Monkey patching a db model class in Rails with Mongoid causes weird behaviour

我正在使用开发脚本文件来检查新的可能想法。最近我试图从该脚本文件中修补 MyDBObject。 假设一个空 dev.rb 文件并在顶部添加一个猴子补丁,如下所示:

class MyDBObject
  def test_function
    'function works'
  end
end

启动 pry 控制台并加载文件会产生随机结果。 我首先收到:

NoMethodError: undefined method `relations' for MyDBObject:Class

稍后加载脚本,但我无法再访问原始 class:

undefined method `first' for MyDBObject:Class

我注意到在行前面:

MyDBObject

就在猴子补丁之前,实现了预期的功能。 这似乎是 class 对象的某种延迟加载。有人可以帮我解释一下吗?

根据加载源文件的顺序,您将重新定义整个 class,或者替换您的更改。

我强烈建议您读一读:http://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/(TLDR - 将您的补丁放入模块中并明确包含它)