1

我正在扩展 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
4

1 回答 1

1

您不需要 InstanceMethods 模块 - 您的模块应该看起来像

module MongoidBridge
  extend ActiveSupport::Concern
  module ClassMethods
  ...
  end

  def create_mongo
  end
end

早期版本的 rails 使用了实例方法模块,但最终认为这是多余的,因为您可以只在封闭模块中定义方法。使用 InstanceMethods 不久前被弃用(可能是 rails 3.2 - 我的记忆很模糊)并随后被删除

于 2015-04-30T23:41:16.527 回答