Sha256: 924b66befc14896e52e8e500805e2d9e0c0dbfde22fe7157b6d48945e57d48ad

Contents?: true

Size: 840 Bytes

Versions: 6

Compression:

Stored size: 840 Bytes

Contents

module Cache
  module Object
    class MultiGet
      attr_reader :clazz

      def initialize(clazz)
        @clazz = clazz
      end

      def fetch_all(ids)
        objs = cached_objects(ids)
        remaining = missed_ids(ids, objs)
        return objs if remaining.empty?
        objs + load_from_db(remaining)
      end

      def load_from_db(ids)
        primary_key = clazz.primary_key.to_sym
        clazz.where(primary_key => ids).to_a.each(&:write_cache!)
      end

      def object_keys(ids)
        ids.map { |id| Cache::Object::KeyGenerator.key_for_object(clazz.name, id) }
      end

      def cached_objects(ids)
        keys = object_keys(ids)
        Cache::Object.adapter.read_multi(keys).values
      end

      def missed_ids(ids, fetched_objects)
        ids - fetched_objects.map(&:id)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
cache-object-0.2.0 lib/cache/object/multi_get.rb
cache-object-0.1.0 lib/cache/object/multi_get.rb
cache-object-0.0.7 lib/cache/object/multi_get.rb
cache-object-0.0.6 lib/cache/object/multi_get.rb
cache-object-0.0.5 lib/cache/object/multi_get.rb
cache-object-0.0.4 lib/cache/object/multi_get.rb