Skip to content

Let cache handle marshalling of results. #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions lib/jsonapi/renderer/cached_resources_processor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,16 @@ module JSONAPI
class Renderer
# @private
class CachedResourcesProcessor < ResourcesProcessor
class JSONString < String
def to_json(*)
self
end
end

def initialize(cache)
@cache = cache
end

def process_resources
[@primary, @included].each do |resources|
cache_hash = cache_key_map(resources)
processed_resources = @cache.fetch_multi(cache_hash.keys) do |key|
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)
res.as_jsonapi(include: include, fields: fields)
end

resources.replace(processed_resources.values)
Expand Down
4 changes: 2 additions & 2 deletions spec/caching_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def initialize
@cache = {}
end

def fetch_multi(keys)
def fetch_multi(*keys)
keys.each_with_object({}) do |k, h|
@cache[k] = yield(k) unless @cache.key?(k)
h[k] = @cache[k]
Expand Down Expand Up @@ -96,6 +96,6 @@ def fetch_multi(keys)
}

expect(JSON.parse(actual.to_json)).to eq(JSON.parse(expected.to_json))
expect(actual[:data]).to be_a(JSONAPI::Renderer::CachedResourcesProcessor::JSONString)
expect(actual[:data]).to be_a(Hash)
end
end