Class: CardDB::MemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/carddb/cache.rb

Overview

Simple in-memory cache with TTL support. Compatible with Rails.cache interface (read/write/delete).

Examples:

cache = CardDB::MemoryCache.new
cache.write("key", "value", expires_in: 60)
cache.read("key")  # => "value"
# After 60 seconds...
cache.read("key")  # => nil

Instance Method Summary collapse

Constructor Details

#initializeMemoryCache

Returns a new instance of MemoryCache.



14
15
16
17
# File 'lib/carddb/cache.rb', line 14

def initialize
  @store = {}
  @mutex = Mutex.new
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Clear all cached values.



72
73
74
75
76
# File 'lib/carddb/cache.rb', line 72

def clear
  @mutex.synchronize do
    @store.clear
  end
end

#delete(key) ⇒ Boolean

Delete a value from the cache.

Parameters:

  • key (String)

    The cache key

Returns:

  • (Boolean)

    true if the key was deleted



55
56
57
58
59
# File 'lib/carddb/cache.rb', line 55

def delete(key)
  @mutex.synchronize do
    !!@store.delete(key)
  end
end

#exist?(key) ⇒ Boolean

Check if a key exists and is not expired.

Parameters:

  • key (String)

    The cache key

Returns:

  • (Boolean)


65
66
67
# File 'lib/carddb/cache.rb', line 65

def exist?(key)
  !read(key).nil?
end

#read(key) ⇒ Object?

Read a value from the cache.

Parameters:

  • key (String)

    The cache key

Returns:

  • (Object, nil)

    The cached value or nil if not found/expired



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/carddb/cache.rb', line 23

def read(key)
  @mutex.synchronize do
    entry = @store[key]
    return nil unless entry

    if entry[:expires_at] && Time.now > entry[:expires_at]
      @store.delete(key)
      return nil
    end

    entry[:value]
  end
end

#sizeInteger

Get the number of cached entries (for debugging).

Returns:

  • (Integer)


81
82
83
84
85
86
87
88
# File 'lib/carddb/cache.rb', line 81

def size
  @mutex.synchronize do
    # Clean up expired entries first
    now = Time.now
    @store.delete_if { |_, entry| entry[:expires_at] && now > entry[:expires_at] }
    @store.size
  end
end

#write(key, value, expires_in: nil) ⇒ Object

Write a value to the cache.

Parameters:

  • key (String)

    The cache key

  • value (Object)

    The value to cache

  • expires_in (Integer, nil) (defaults to: nil)

    TTL in seconds (nil = no expiry)

Returns:

  • (Object)

    The cached value



43
44
45
46
47
48
49
# File 'lib/carddb/cache.rb', line 43

def write(key, value, expires_in: nil)
  @mutex.synchronize do
    expires_at = expires_in ? Time.now + expires_in : nil
    @store[key] = { value: value, expires_at: expires_at }
    value
  end
end