Module: WorkOS::Cache

Defined in:
lib/workos/cache.rb

Overview

The Cache module provides a simple in-memory cache for storing values This module is not meant to be instantiated in a user space, and is used internally by the SDK

Defined Under Namespace

Classes: Entry

Class Method Summary collapse

Class Method Details

.clearObject

Clears all values from the cache



74
75
76
# File 'lib/workos/cache.rb', line 74

def clear
  store.clear
end

.delete(key) ⇒ Object

Deletes a value from the cache

Parameters:

  • key (String)

    The key to delete the value for



69
70
71
# File 'lib/workos/cache.rb', line 69

def delete(key)
  store.delete(key)
end

.exist?(key) ⇒ Boolean

Checks if a value exists in the cache

Parameters:

  • key (String)

    The key to check for

Returns:

  • (Boolean)

    True if the value exists and has not expired, false otherwise



81
82
83
84
# File 'lib/workos/cache.rb', line 81

def exist?(key)
  entry = store[key]
  !(entry.nil? || entry.expired?)
end

.fetch(key, expires_in: nil, force: false, &block) ⇒ Object

Fetches a value from the cache, or calls the block to fetch the value if it is not present

Parameters:

  • key (String)

    The key to fetch the value for

  • expires_in (Integer) (defaults to: nil)

    The expiration time for the value in seconds

  • force (Boolean) (defaults to: false)

    If true, the value will be fetched from the block even if it is present in the cache

  • block (Proc)

    The block to call to fetch the value if it is not present in the cache

Returns:

  • (Object)

    The value fetched from the cache or the block



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/workos/cache.rb', line 35

def fetch(key, expires_in: nil, force: false, &block)
  entry = store[key]

  if force || entry.nil? || entry.expired?
    value = block.call
    store[key] = Entry.new(value, expires_in)
    return value
  end

  entry.value
end

.read(key) ⇒ Object

Reads a value from the cache

Parameters:

  • key (String)

    The key to read the value for

Returns:

  • (Object)

    The value read from the cache, or nil if the value is not present or has expired



50
51
52
53
54
55
# File 'lib/workos/cache.rb', line 50

def read(key)
  entry = store[key]
  return nil if entry.nil? || entry.expired?

  entry.value
end

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

Writes a value to the cache

Parameters:

  • key (String)

    The key to write the value for

  • value (Object)

    The value to write to the cache

  • expires_in (Integer) (defaults to: nil)

    The expiration time for the value in seconds

Returns:

  • (Object)

    The value written to the cache



62
63
64
65
# File 'lib/workos/cache.rb', line 62

def write(key, value, expires_in: nil)
  store[key] = Entry.new(value, expires_in)
  value
end