Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions spec/stores/memory_store_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions src/lucky_cache/stores/memory_store.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -75,6 +80,7 @@ module LuckyCache
end
end

# The total number of items in the cache.
def size : Int32
@cache.size
end
Expand Down
Loading