Skip to content

Commit b22ee64

Browse files
aeroastrojeremy
authored andcommitted
MemCacheStore: Support expiring counters
Support `expires_in` in `ActiveSupport::Cache::MemCacheStore#increment` and `#decrement`. Closes #30716.
1 parent ae7593e commit b22ee64

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

activesupport/CHANGELOG.md

+13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
* MemCacheStore: Support expiring counters.
2+
3+
Pass `expires_in: [seconds]` to `#increment` and `#decrement` options
4+
to set the Memcached TTL (time-to-live) if the counter doesn't exist.
5+
If the counter exists, Memcached doesn't extend its expiry when it's
6+
incremented or decremented.
7+
8+
```
9+
Rails.cache.increment("my_counter", 1, expires_in: 2.minutes)
10+
```
11+
12+
*Takumasa Ochi*
13+
114
* Handle `TZInfo::AmbiguousTime` errors
215
316
Make `ActiveSupport::TimeWithZone` match Ruby's handling of ambiguous

activesupport/lib/active_support/cache/mem_cache_store.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def increment(name, amount = 1, options = nil)
122122
options = merged_options(options)
123123
instrument(:increment, name, amount: amount) do
124124
rescue_error_with nil do
125-
@data.incr(normalize_key(name, options), amount)
125+
@data.incr(normalize_key(name, options), amount, options[:expires_in])
126126
end
127127
end
128128
end
@@ -135,7 +135,7 @@ def decrement(name, amount = 1, options = nil)
135135
options = merged_options(options)
136136
instrument(:decrement, name, amount: amount) do
137137
rescue_error_with nil do
138-
@data.decr(normalize_key(name, options), amount)
138+
@data.decr(normalize_key(name, options), amount, options[:expires_in])
139139
end
140140
end
141141
end

activesupport/test/cache/stores/mem_cache_store_test.rb

+16
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,22 @@ def test_local_cache_raw_values
5757
end
5858
end
5959

60+
def test_increment_expires_in
61+
cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
62+
cache.clear
63+
assert_called_with cache.instance_variable_get(:@data), :incr, [ "foo", 1, 60 ] do
64+
cache.increment("foo", 1, expires_in: 60)
65+
end
66+
end
67+
68+
def test_decrement_expires_in
69+
cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
70+
cache.clear
71+
assert_called_with cache.instance_variable_get(:@data), :decr, [ "foo", 1, 60 ] do
72+
cache.decrement("foo", 1, expires_in: 60)
73+
end
74+
end
75+
6076
def test_local_cache_raw_values_with_marshal
6177
cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true)
6278
cache.clear

0 commit comments

Comments
 (0)