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