Class: JSONAPI::Renderer::CachedResourcesProcessor

Inherits:
ResourcesProcessor show all
Defined in:
lib/jsonapi/renderer/cached_resources_processor.rb

Defined Under Namespace

Classes: JSONString

Instance Method Summary collapse

Methods inherited from ResourcesProcessor

#process

Constructor Details

#initialize(cache) ⇒ CachedResourcesProcessor

Returns a new instance of CachedResourcesProcessor.



13
14
15
# File 'lib/jsonapi/renderer/cached_resources_processor.rb', line 13

def initialize(cache)
  @cache = cache
end

Instance Method Details

#cache_key_map(resources) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/jsonapi/renderer/cached_resources_processor.rb', line 36

def cache_key_map(resources)
  resources.each_with_object({}) do |res, h|
    ri = [res.jsonapi_type, res.jsonapi_id]
    include_dir = @include_rels[ri]
    fields = @fields[ri.first.to_sym]
    h[res.jsonapi_cache_key(include: include_dir, fields: fields)] =
      [res, include_dir, fields]
  end
end

#process_resourcesObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/jsonapi/renderer/cached_resources_processor.rb', line 17

def process_resources
  # NOTE(beauby): This is necessary for cache keys consistency.
  @include_rels = @include_rels.each_with_object({}) do |(k, v), h|
    h[k] = v.to_a.sort!
  end

  [@primary, @included].each do |resources|
    cache_hash = cache_key_map(resources)
    processed_resources = @cache.fetch_multi(*cache_hash.keys) do |key|
      res, include, fields = cache_hash[key]
      json = res.as_jsonapi(include: include, fields: fields).to_json

      JSONString.new(json)
    end

    resources.replace(processed_resources.values)
  end
end