Skip to content

Commit

Permalink
Added more specs and better logic for cache_prefix_key
Browse files Browse the repository at this point in the history
  • Loading branch information
jlurena committed Jul 11, 2024
1 parent 60df81c commit 5fcc5b3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
8 changes: 7 additions & 1 deletion lib/cached_resource/caching.rb
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,13 @@ def cache_key(*arguments)

def name_key
@name_key ||= begin
prefix = cached_resource.cache_key_prefix.nil? ? "" : "#{cached_resource.cache_key_prefix}/"
prefix = if cached_resource.cache_key_prefix.nil?
""
elsif cached_resource.cache_key_prefix.respond_to?(:call)
cached_resource.cache_key_prefix.call
else
"#{cached_resource.cache_key_prefix}/"
end
prefix + name.parameterize.tr("-", "/")
end
end
Expand Down
34 changes: 30 additions & 4 deletions spec/cached_resource/caching_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -266,16 +266,42 @@ def read_from_cache(key, model = Thing)
context "when cache prefix is set" do
before do
Thing.instance_variable_set(:@name_key, nil) # Remove memoization
allow(thing_cached_resource).to receive(:cache_key_prefix).and_return("prefix123")
end

after do
Thing.instance_variable_set(:@name_key, nil) # Remove memoization
end

it "caches with the cache_key_prefix" do
result = Thing.find(1)
expect(read_from_cache("prefix123/thing/1")).to eq(result)
context "cache_key_prefix is a string" do
before { allow(thing_cached_resource).to receive(:cache_key_prefix).and_return("prefix123") }
it "caches with the cache_key_prefix" do
result = Thing.find(1)
expect(read_from_cache("prefix123/thing/1")).to eq(result)
end
end

context "cache_key_prefix is a callable" do
before do
# Gets called 3 times
allow(thing_cached_resource).to receive(:cache_key_prefix)
.and_return(
proc { "prefix123/" },
proc { "prefix123/" },
proc { "prefix123/" },
proc { "prefix456/" },
proc { "prefix456/" },
proc { "prefix456/" }
)
end

it "caches with the cache_key_prefix" do
result = Thing.find(1)
expect(read_from_cache("prefix123/thing/1")).to eq(result)
# Test for dynamicness
Thing.instance_variable_set(:@name_key, nil) # Remove memoization
result = Thing.find(1, reload: true)
expect(read_from_cache("prefix456/thing/1")).to eq(result)
end
end
end

Expand Down

0 comments on commit 5fcc5b3

Please sign in to comment.