gpt4 book ai didi

ruby-on-rails - 重写的方法仍然被调用

转载 作者:数据小太阳 更新时间:2023-10-29 08:09:15 24 4
gpt4 key购买 nike

我正在使用一个在数据库中的两个条目之间实现 belongs_to 关联的库。因为这不是我需要的行为,所以我想通过 prepend 覆盖这个方法。但是 pry 告诉我原来的方法还是被调用了。我仔细检查了一下,我使用的是 ruby​​ 2.0。

前面的代码:

module Associations
module ClassMethods

[...]
#Add the attributeName to the belongsToAttributes
#and add a field in the list for the IDs
def belongs_to(attr_name)
@belongsToAttributes ||= []
@belongstoAttributes << attr_name

create_attr attr_name.to_s
attribute belongs_to_string.concat(attr_name.to_s).to_sym
end

def belongsToAttributes
@belongsToAttributes
end
end

def self.included(base)
base.extend(ClassMethods)
end
end

# prepend the extension
Couchbase::Model.send(:prepend, Associations)

我在这个类中使用这个:

注意:我也试过直接重写这个类中的方法还是不行

require 'couchbase/model'

class AdServeModel < Couchbase::Model

[...]
#I tried to add the belongs_to method like this
#def belongs_to(attr_name)
# @belongsToAttributes ||= []
# @belongstoAttributes << attr_name

# create_attr attr_name.to_s
# attribute belongs_to_string.concat(attr_name.to_s).to_sym
# end

# def belongsToAttributes
# @belongsToAttributes
# end
end

当我用 pry 检查时,它显示我最终在 this 中方法调用:

def self.belongs_to(name, options = {})
ref = "#{name}_id"
attribute(ref)
assoc = name.to_s.camelize.constantize
define_method(name) do
assoc.find(self.send(ref))
end
end

如能指出我做错了什么,我们将不胜感激。

编辑:好的,我这样解决了问题:

 self.prepended(base)
class << base
prepend ClassMethods
end
end

end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)

由于 Arie Shaw 的帖子包含解决此问题的重要指示,我将接受他的回答。尽管他错过了关于扩展和前置我想调用的方法的要点。有关我在方法前面遇到的麻烦的更详细讨论,请参阅 this问题。

最佳答案

根据您发布的 pry trace,您想要猴子补丁的方法是 AdServeModel 的类方法,而不是实例方法。

  • Associations 模块方法的问题是,您正在调用 Module#prepend 将模块prepend 到现有类,但是,您编写了一个 self.included Hook 方法,该方法仅在包含模块(而不是前置)时调用。你应该写 Module#prepended Hook 。

  • 直接覆盖方法的问题在于,您实际上覆盖的是实例方法,而不是类方法。它应该是这样的:

require 'couchbase/model'

class AdServeModel < Couchbase::Model
class << self
# save the original method for future use, if necessary
alias_method :orig_belongs_to, :belongs_to

def belongs_to(attr_name)
@belongsToAttributes ||= []
@belongstoAttributes << attr_name

create_attr attr_name.to_s
attribute belongs_to_string.concat(attr_name.to_s).to_sym
end

def belongsToAttributes
@belongsToAttributes
end
end
end

关于ruby-on-rails - 重写的方法仍然被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com