我正在扩展 ActiveRecord::Base。在我的 lib 文件夹中,我有一个文件 mongoid_bridge.rb:
module MongoidBridge
extend ActiveSupport::Concern
module ClassMethods
...
end
module InstanceMethods
...
def create_mongo(klass, fields)
...
end
end
end
ActiveRecord::Base.send(:include, MongoidBridge)
在 config/initializers 中,我有两个文件,为了以正确的顺序读取,每个文件都以 01、02 等为前缀。在 01_mongo_mixer.rb 中,我有以下内容:
require "active_record_bridge"
require "mongoid_bridge"
然后在 02_model_initializer.rb 中,我有以下内容:
MyActiveRecordModel.all.each do |model|
model.create_mongo(some_klass, some_fields)
end
model 是 ActiveRecord 子类的实例,因此它应该在查找链中找到 create_mongo 实例方法。但是,它没有找到它,因为我收到以下错误:
Uncaught exception: undefined method `create_mongo' for #<MyActiveRecordModel:0x007fff1f5e5e18>
为什么找不到实例方法?
更新:
好像包含了ClassMethods下的方法,但不包含InstanceMethods下的方法:
singleton_respond = MyActiveRecordModel.respond_to? :has_many_documents
# => true
instance_respond = MyActiveRecordModel.new.respond_to? :create_mongo
# => false