Class: BulkCacheFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/bulk_cache_fetcher.rb

Overview

Fetches many objects from a cache in order. In the event that some objects can’t be served from the cache, you will have the opportunity to fetch them in bulk. This allows you to preload and cache entire object hierarchies, which works particularly well with Rails’ nested caching while avoiding the n+1 queries problem in the uncached case.

Constant Summary collapse

VERSION =
'1.0.0'

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ BulkCacheFetcher

Creates a new bulk cache fetcher, backed by cache. Cache must respond to the standard Rails cache API, described on guides.rubyonrails.org/caching_with_rails.html



13
14
15
# File 'lib/bulk_cache_fetcher.rb', line 13

def initialize(cache)
  @cache = cache
end

Instance Method Details

#fetch(object_identifiers, options = {}, &finder_block) ⇒ Object

Returns a list of objects identified by object_identifiers. fetch will try to find the objects from the cache first. Identifiers for objects that aren’t in the cache will be passed as an ordered list to finder_block, where you can find the objects as you see fit. These objects should be returned in the same order as the identifiers that were passed into the block, because they’ll be cached under their respective keys. The objects returned by fetch will be returned in the same order as the object_identifiers passed in.

options will be passed along unmodified when caching newly found objects, so you can use it for things like setting cache expiration.



30
31
32
33
34
35
# File 'lib/bulk_cache_fetcher.rb', line 30

def fetch(object_identifiers, options = {}, &finder_block)
  object_identifiers = normalize(object_identifiers)
  cached_keys_with_objects, uncached_identifiers = partition(object_identifiers)
  found_objects = find(uncached_identifiers, options, &finder_block)
  coalesce(cache_keys(object_identifiers), cached_keys_with_objects, found_objects)
end