From db9ae5f1e1449b09c08d55a8a3a21ff61d904bd3 Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Sun, 14 May 2017 23:24:37 +0100 Subject: [PATCH] Don't cache locally if unless_exist was passed Some cache backends support the `unless_exist` option, which tells them not to overwrite an existing entry. The local cache currently always stores the new value, even though the backend may have rejected it. Since we can't tell which value will end up in the backend cache, we should delete the key from the local cache, so that the next read for that key will go to the backend and pick up the correct value. --- .../lib/active_support/cache/strategy/local_cache.rb | 7 ++++++- activesupport/test/caching_test.rb | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb index 672eb2bb8054a..91875a56f557a 100644 --- a/activesupport/lib/active_support/cache/strategy/local_cache.rb +++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb @@ -115,7 +115,12 @@ def read_entry(key, options) end def write_entry(key, entry, options) - local_cache.write_entry(key, entry, options) if local_cache + if options[:unless_exist] + local_cache.delete_entry(key, options) if local_cache + else + local_cache.write_entry(key, entry, options) if local_cache + end + super end diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index c67ffe69b80a5..dbec684ce0dbc 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -708,6 +708,14 @@ def test_local_cache_of_write_nil end end + def test_local_cache_of_write_with_unless_exist + @cache.with_local_cache do + @cache.write("foo", "bar") + @cache.write("foo", "baz", unless_exist: true) + assert_equal @peek.read("foo"), @cache.read("foo") + end + end + def test_local_cache_of_delete @cache.with_local_cache do @cache.write("foo", "bar")