Skip to content

Commit

Permalink
Set ttl for redis and memcache cache stores when using expires_at
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed May 10, 2022
1 parent da05fa3 commit ded8301
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions activesupport/lib/active_support/cache.rb
Expand Up @@ -678,6 +678,13 @@ def delete_multi_entries(entries, **options)
def merged_options(call_options)
if call_options
call_options = normalize_options(call_options)
if call_options.key?(:expires_in) && call_options.key?(:expires_at)
raise ArgumentError, "Either :expires_in or :expires_at can be supplied, but not both"
end

expires_at = call_options.delete(:expires_at)
call_options[:expires_in] = (expires_at - Time.now) if expires_at

if options.empty?
call_options
else
Expand Down
8 changes: 8 additions & 0 deletions activesupport/test/cache/behaviors/cache_store_behavior.rb
Expand Up @@ -536,6 +536,14 @@ def test_expired_in_is_alias_for_expires_in
end
end

def test_expires_in_and_expires_at
key = SecureRandom.uuid
error = assert_raises(ArgumentError) do
@cache.write(key, "bar", expire_in: 60, expires_at: 1.minute.from_now)
end
assert_equal "Either :expires_in or :expires_at can be supplied, but not both", error.message
end

def test_race_condition_protection_skipped_if_not_defined
key = SecureRandom.alphanumeric
@cache.write(key, "bar")
Expand Down
10 changes: 10 additions & 0 deletions activesupport/test/cache/stores/mem_cache_store_test.rb
Expand Up @@ -127,6 +127,16 @@ def test_local_cache_raw_values
end
end

def test_write_expires_at
cache = lookup_store(raw: true, namespace: nil)

Time.stub(:now, Time.now) do
assert_called_with client(cache), :set, [ "key_with_expires_at", "bar", 30 * 60, Hash ] do
cache.write("key_with_expires_at", "bar", expires_at: 30.minutes.from_now)
end
end
end

def test_increment_expires_in
cache = lookup_store(raw: true, namespace: nil)
assert_called_with client(cache), :incr, [ "foo", 1, 60 ] do
Expand Down
5 changes: 5 additions & 0 deletions activesupport/test/cache/stores/redis_cache_store_test.rb
Expand Up @@ -179,6 +179,11 @@ def test_fetch_multi_without_names
end
end

def test_write_expires_at
@cache.write "key_with_expires_at", "bar", expires_at: 30.minutes.from_now
assert @cache.redis.ttl("#{@namespace}:key_with_expires_at") > 0
end

def test_increment_expires_in
assert_called_with @cache.redis, :incrby, [ "#{@namespace}:foo", 1 ] do
assert_called_with @cache.redis, :expire, [ "#{@namespace}:foo", 60 ] do
Expand Down

0 comments on commit ded8301

Please sign in to comment.