Sha256: cbbab597f4cc1601e2ae96e66a99fc467f44fc86e309bcd6abfb27381716e3f1

Contents?: true

Size: 1.1 KB

Versions: 19

Compression:

Stored size: 1.1 KB

Contents

require 'set'

module Fiona7
  module Prefetch
    class ObjPrefetch
      def initialize(klass, prefetch_ids=[])
        self.klass          = klass
        self.prefetched_ids = Set.new
        self.object_id_map  = {}

        self.prefetch_objects(prefetch_ids)
      end

      # Returns an object with given ID or nil if no matching object found
      def find_one(id)
        self.find_many([id]).first
      end

      # Returns an array with objects for given IDs.
      # The array is ordered according to the IDs given.
      # For missing objects the array is filled with nil values
      def find_many(ids)
        self.prefetch_objects(ids)
        ids.map { |id| self.object_id_map[id.to_i] }
      end

      protected
      attr_accessor :klass, :prefetched_ids, :object_id_map

      def prefetch_objects(prefetch_ids)
        missing = prefetch_ids.select {|id| !self.prefetched_ids.include?(id) }

        return if missing.empty?

        self.klass.where(obj_id: missing).each do |obj|
          self.prefetched_ids << obj.id
          self.object_id_map[obj.id] = obj
        end
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
infopark_fiona7-1.6.1.1.5 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.6.1.1.1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.6.1.1.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.2.3 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.2.1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.2.2 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.5.5.1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.5.5.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.1.4 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.5.4.1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.5.4.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.1.3 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.5.3.1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.4.3.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.3.2.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.3.2.0.pre.beta1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.2.1.0.pre.beta1 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.5.2.0.0 lib/fiona7/prefetch/obj_prefetch.rb
infopark_fiona7-1.2.0.1.1 lib/fiona7/prefetch/obj_prefetch.rb