简体   繁体   English

猴子用Mongoid修补Rails中的db模型类会导致奇怪的行为

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

I am using a development script file to check out new possible ideas. 我正在使用开发脚本文件来检查新的可能想法。 Recently I tried to monkey patch MyDBObject from within that script file. 最近,我尝试从该脚本文件中猴子MyDBObject补丁。 Assume an empty dev.rb file and add a monkey patch right in the top like so: 假设一个空的dev.rb文件,并在顶部添加一个猴子补丁,如下所示:

class MyDBObject
  def test_function
    'function works'
  end
end

Starting up the pry console and loading the file yields random results. 启动撬控制台并加载文件会产生随机结果。 First I received: 首先我收到:

NoMethodError: undefined method `relations' for MyDBObject:Class

Later the script loaded, but I couldn't access the original class any longer: 后来加载了脚本,但是我再也无法访问原始类了:

undefined method `first' for MyDBObject:Class

I noticed that prepending the line: 我注意到在该行之前:

MyDBObject

right before the monkey patching, the intended functionality is achieved. 在猴子修补之前,就可以实现预期的功能。 This appears to be some sort of lazy loading of the class objects. 这似乎是类对象的某种延迟加载。 Can somebody cast some light on this for me please? 有人可以帮我这个忙吗?

Depending on the order in which source files are loaded, you'll either be redefining the entire class, or having your changes replaced. 根据源文件的加载顺序,您将重新定义整个类,或者替换您的更改。

I highly recommend giving this a read: http://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/ (TLDR - put your patch in a module and explicitly include it) 我强烈建议您阅读以下内容: http ://www.justinweiss.com/articles/3-ways-to-monkey-patch-without-making-a-mess/(TLDR-将您的补丁放入模块中,并明确包含它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM