Class: RackJwtVerifier::InProcessCache

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_jwt_verifier/in_process_cache.rb

Overview

A simple, thread-safe, in-memory cache implementation designed to mimic a real cache store (like Rails.cache or Redis) but without external dependencies. This is the default cache store used if the user doesn’t configure one.

Constant Summary collapse

DEFAULT_EXPIRY =

The cache lifespan in seconds (5 minutes)

300

Instance Method Summary collapse

Constructor Details

#initializeInProcessCache

Returns a new instance of InProcessCache.



11
12
13
14
# File 'lib/rack_jwt_verifier/in_process_cache.rb', line 11

def initialize
  @store = {}
  @lock = Mutex.new # Ensure thread safety for multi-threaded environments
end

Instance Method Details

#delete(key) ⇒ Object?

Deletes an entry from the cache.

Parameters:

  • key (String)

    The cache key.

Returns:

  • (Object, nil)

    The deleted entry value or nil.



50
51
52
53
54
# File 'lib/rack_jwt_verifier/in_process_cache.rb', line 50

def delete(key)
  @lock.synchronize do
    @store.delete(key)
  end
end

#read(key) ⇒ Object?

Reads the value for a given key. Automatically checks for expiry.

Parameters:

  • key (String)

    The cache key.

Returns:

  • (Object, nil)

    The cached value or nil if expired or not found.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rack_jwt_verifier/in_process_cache.rb', line 19

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

    value, expires_at = entry
    
    # Check if the entry is expired
    return nil if Time.now.to_i >= expires_at
    
    value
  end
end

#write(key, value, options = {}) ⇒ Object

Writes a value to the cache with an optional expiration time.

Parameters:

  • key (String)

    The cache key.

  • value (Object)

    The value to store.

  • options (Hash) (defaults to: {})

    Options, expecting :expires_in (seconds).

Returns:

  • (Object)

    The stored value.



38
39
40
41
42
43
44
45
# File 'lib/rack_jwt_verifier/in_process_cache.rb', line 38

def write(key, value, options = {})
  @lock.synchronize do
    expiry = options[:expires_in] || DEFAULT_EXPIRY
    expires_at = Time.now.to_i + expiry
    @store[key] = [value, expires_at]
    value
  end
end