Sha256: 2ba81d5b981c03cb5e8853e5d744e3ac2ac20a3d55c5798e5692b984b2f072c5

Contents?: true

Size: 1.6 KB

Versions: 4

Compression:

Stored size: 1.6 KB

Contents

module Bullet
  module Mongoid
    def self.enable
      require 'mongoid'
      ::Mongoid::Contextual::Mongo.class_eval do
        alias_method :origin_first, :first
        alias_method :origin_last, :last
        alias_method :origin_each, :each
        alias_method :origin_eager_load, :eager_load

        def first
          result = origin_first
          Bullet::Detector::Association.add_impossible_object(result)
          result
        end

        def last
          result = origin_last
          Bullet::Detector::Association.add_impossible_object(result)
          result
        end

        def each(&block)
          records = query.map{ |doc| ::Mongoid::Factory.from_db(klass, doc) }
          if records.length > 1
            Bullet::Detector::Association.add_possible_objects(records)
          elsif records.size == 1
            Bullet::Detector::Association.add_impossible_object(records.first)
          end
          origin_each(&block)
        end

        def eager_load(docs)
          associations = criteria.inclusions.map(&:name)
          docs.each do |doc|
            Bullet::Detector::Association.add_object_associations(doc, associations)
          end
          Bullet::Detector::Association.add_eager_loadings(docs, associations)
          origin_eager_load(docs)
        end
      end

      ::Mongoid::Relations::Accessors.class_eval do
        alias_method :origin_set_relation, :set_relation

        def set_relation(name, relation)
          Bullet::Detector::NPlusOneQuery.call_association(self, name)
          origin_set_relation(name, relation)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bullet-4.1.3 lib/bullet/mongoid3.rb
bullet-4.1.2 lib/bullet/mongoid3.rb
bullet-4.1.1 lib/bullet/mongoid3.rb
bullet-4.1.0 lib/bullet/mongoid3.rb