Sha256: 1b45b8f87eb606350bfdaf647eb58637c41375561067f5f378d30b187a1a8d5d

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

require "mongoid/bulk/import/version"
require 'mongoid'

module Mongoid
  module Bulk
    module Import
      extend ActiveSupport::Concern
      Result = Struct.new(:failed_instances, :num_inserts, :ids)

      def bulk_insert(attributes = nil, options = {}, &block)
        _creating do
          if attributes.is_a?(::Array)
            documents = attributes.map { |attrs| bulk_insert_obj(attrs, options, &block) }
          else
            documents = [bulk_insert_obj(attributes, options, &block)]
          end
          valid_documents, invalid_documents = documents.partition { |doc| doc.errors.none? }
          response = collection.insert_many(valid_documents.map(&:as_document)) unless valid_documents.blank?
          Result.new(invalid_documents, response&.inserted_count || 0, response&.inserted_ids || [])
        end
      end

      def bulk_insert_obj(attributes = nil, options = {}, &block)
        doc = new(attributes, &block)
        doc.valid? if (options[:validate].nil? ? true : options[:validate])
        doc
      end
    end
  end
end
Mongoid::Document::ClassMethods.send(:include, Mongoid::Bulk::Import)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-bulk-import-0.2.0 lib/mongoid/bulk/import.rb