简体   繁体   English

在Ruby中使用模块扩展对象时的奇怪行为

[英]Odd behaviour when extending an object with a module in ruby

If I do the following: 如果我执行以下操作:

user = User.new
user.extend Customer
user.is_a? Customer == true

it works fine. 它工作正常。

However if I do the following (where Profile is a mongoid model and user is embedded): 但是,如果我执行以下操作(其中Profile是一个mongoid模型,并且嵌入了用户):

profile = Profile.all.first
profile.user.extend Customer
profile.user.is_a? Customer == false

user is no longer a customer. 用户不再是客户。 There must be a simple reason for this but I can't see it. 一定有一个简单的原因,但我看不到。

Edit: User and Profile are mongoid Models, ie. 编辑:用户和配置文件是mongoid模型,即。 profile.user.class = User and profile.class = Profile. profile.user.class =用户和profile.class =配置文件。

My guess: every time you call profile.user you are getting a new object. 我的猜测:每次调用profile.user都会得到一个新对象。 Try: 尝试:

2.times{ p profiler.user.object_id }

and see what happens. 看看会发生什么。 Then try: 然后尝试:

u = profile.user
u.extend Customer
p u.is_a? Customer
p profile.user.is_a? Customer

and see what output you get. 看看你得到什么输出。

This actually ended up being a bug in Mongoid. 这实际上最终是Mongoid中的错误。 Here is the issue with description: https://github.com/mongoid/mongoid/issues/1933 这是描述问题: https : //github.com/mongoid/mongoid/issues/1933

It is now fixed in the latest commit. 现在已在最新提交中修复。

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

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