Class: Underpass::Cache

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

Overview

Simple in-memory cache with TTL expiration.

Examples:

Enable caching

Underpass.cache = Underpass::Cache.new(ttl: 600)

Instance Method Summary collapse

Constructor Details

#initialize(ttl: 300) ⇒ Cache

Creates a new cache instance.

Parameters:

  • ttl (Integer) (defaults to: 300)

    time-to-live in seconds for cached entries (default: 300)



12
13
14
15
# File 'lib/underpass/cache.rb', line 12

def initialize(ttl: 300)
  @store = {}
  @ttl = ttl
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Removes all entries from the cache.



41
42
43
# File 'lib/underpass/cache.rb', line 41

def clear
  @store.clear
end

#fetch(key) ⇒ Object?

Retrieves a cached value by key if it has not expired.

Parameters:

  • key (String)

    the cache key

Returns:

  • (Object, nil)

    the cached value, or nil if missing or expired



21
22
23
24
25
26
27
# File 'lib/underpass/cache.rb', line 21

def fetch(key)
  entry = @store[key]
  return nil unless entry
  return nil if Time.now - entry[:time] > @ttl

  entry[:value]
end

#store(key, value) ⇒ Hash

Stores a value in the cache.

Parameters:

  • key (String)

    the cache key

  • value (Object)

    the value to cache

Returns:

  • (Hash)

    the stored entry



34
35
36
# File 'lib/underpass/cache.rb', line 34

def store(key, value)
  @store[key] = { value: value, time: Time.now }
end