Ruby on rails 仍然会调用重写的方法
我使用的库正在实现数据库中两个条目之间的Ruby on rails 仍然会调用重写的方法,ruby-on-rails,ruby,couchbase,ruby-2.0,Ruby On Rails,Ruby,Couchbase,Ruby 2.0,我使用的库正在实现数据库中两个条目之间的关联。因为这不是我需要的行为,所以我想通过prepend重写此方法。但是pry告诉我原始方法仍然被调用。我仔细检查了一下,使用的是ruby 2.0 添加前缀的代码: module Associations module ClassMethods [...] #Add the attributeName to the belongsToAttributes #and add a field in the list for the
关联。因为这不是我需要的行为,所以我想通过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)
任何关于我做错了什么的指点都将不胜感激
编辑:
好的,我这样解决了这个问题:
self.prepended(base)
class << base
prepend ClassMethods
end
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)
self.prepend(基本)
class根据您发布的pry跟踪,您想要使用的方法是AdServeModel
的class方法,而不是实例方法
- 您的
关联
模块方法的问题是,您正在调用module#prepend
以prepend
将模块添加到现有类中,但是,您编写了一个self.included
钩子方法,该方法仅在包含模块(不包含前缀)时才会调用。你应该改为写hook
- 直接重写方法的问题是,您实际上重写的是实例方法,而不是类方法。应该是这样的:
self.prepended(base)
class << base
prepend ClassMethods
end
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)
需要“couchbase/model”
类AdServeModel 类哦,是的,我明白了,我想它叫alias\u method\u chaining
?事实上,我试图避免这种情况。我已经将钩子更改为Module#prepend,但可惜没有成功。请参考我试图找到更基本问题答案的问题。
self.prepended(base)
class << base
prepend ClassMethods
end
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)