Skip to content

Commit 75f13e6

Browse files
authored
Ensure expired items are removed from the cache when they're read. Fixes #19 (#20)
1 parent 04e668a commit 75f13e6

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

spec/stores/memory_store_spec.cr

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,21 @@ describe LuckyCache::MemoryStore do
204204
cache.read("key").should eq(nil)
205205
end
206206
end
207+
208+
it "evicts expired items from the cache to free memory" do
209+
cache = LuckyCache::MemoryStore.new
210+
cache.write("key1", expires_in: 1.minute) { "data1" }
211+
cache.write("key2", expires_in: 5.minutes) { "data2" }
212+
cache.size.should eq(2)
213+
214+
Timecop.travel(90.seconds.from_now) do
215+
cache.read("key1").should eq(nil)
216+
cache.size.should eq(1)
217+
218+
cache.read("key2").should_not be_nil
219+
cache.size.should eq(1)
220+
end
221+
end
207222
end
208223

209224
describe "#delete" do

src/lucky_cache/stores/memory_store.cr

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@ module LuckyCache
77
end
88

99
# Returns the `CacheItem` or nil if the `key` is not found.
10-
# If the key is found, but the item is expired, it returns nil.
10+
# If the key is found, but the item is expired, remove it and return nil.
1111
def read(key : CacheKey) : CacheItem?
1212
if item = cache[key]?
13-
item.expired? ? nil : item
13+
if item.expired?
14+
cache.delete(key)
15+
nil
16+
else
17+
item
18+
end
1419
end
1520
end
1621

@@ -75,6 +80,7 @@ module LuckyCache
7580
end
7681
end
7782

83+
# The total number of items in the cache.
7884
def size : Int32
7985
@cache.size
8086
end

0 commit comments

Comments
 (0)