diff --git a/spec/stores/memory_store_spec.cr b/spec/stores/memory_store_spec.cr index 14f5350..6be2a5b 100644 --- a/spec/stores/memory_store_spec.cr +++ b/spec/stores/memory_store_spec.cr @@ -204,6 +204,21 @@ describe LuckyCache::MemoryStore do cache.read("key").should eq(nil) end end + + it "evicts expired items from the cache to free memory" do + cache = LuckyCache::MemoryStore.new + cache.write("key1", expires_in: 1.minute) { "data1" } + cache.write("key2", expires_in: 5.minutes) { "data2" } + cache.size.should eq(2) + + Timecop.travel(90.seconds.from_now) do + cache.read("key1").should eq(nil) + cache.size.should eq(1) + + cache.read("key2").should_not be_nil + cache.size.should eq(1) + end + end end describe "#delete" do diff --git a/src/lucky_cache/stores/memory_store.cr b/src/lucky_cache/stores/memory_store.cr index 1926f93..70603ea 100644 --- a/src/lucky_cache/stores/memory_store.cr +++ b/src/lucky_cache/stores/memory_store.cr @@ -7,10 +7,15 @@ module LuckyCache end # Returns the `CacheItem` or nil if the `key` is not found. - # If the key is found, but the item is expired, it returns nil. + # If the key is found, but the item is expired, remove it and return nil. def read(key : CacheKey) : CacheItem? if item = cache[key]? - item.expired? ? nil : item + if item.expired? + cache.delete(key) + nil + else + item + end end end @@ -75,6 +80,7 @@ module LuckyCache end end + # The total number of items in the cache. def size : Int32 @cache.size end