我正在使用一个正在实现的库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)
我在这堂课中使用这个:
Note:我也尝试直接重写这个类中的方法,但仍然没有发生
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 https://github.com/couchbase/couchbase-ruby-model/blob/master/lib/couchbase/model.rb#L386方法调用:
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
任何指出我做错了什么的指示将不胜感激。
Edit:好吧,我这样解决了这个问题:
self.prepended(base)
class << base
prepend ClassMethods
end
end
end
# prepend the extension
Couchbase::Model.send(:prepend, Associations)
Since 阿里·肖的帖子包含解决这个问题的重要指示,我会接受他的回答。尽管他错过了关于扩展和前置我想要调用的方法的要点。有关我在添加方法时遇到的问题的更详细讨论,请参阅this https://stackoverflow.com/questions/18683750/how-to-prepend-classmethods问题。