Class: ApiWrapper::Cache::CacheStore

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

Overview

CacheStore class provides an in-memory caching mechanism.

Instance Method Summary collapse

Constructor Details

#initializeCacheStore

Returns a new instance of CacheStore.



7
8
9
# File 'lib/api_wrapper/cache/cache_store.rb', line 7

def initialize
  @store = {}
end

Instance Method Details

#delete(key) ⇒ Object

Deletes data from the cache.

Parameters:

  • key (String)

    The cache key.



47
48
49
# File 'lib/api_wrapper/cache/cache_store.rb', line 47

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

#fetch(key, ttl) { ... } ⇒ Object

Retrieves the cached data for the given key, or fetches fresh data if not cached or expired.

Parameters:

  • key (String)

    The cache key.

  • ttl (Integer)

    The time-to-live in seconds.

Yields:

  • Fetches fresh data if cache is expired or not present.

Returns:

  • (Object)

    The cached data or the result of the block if not cached or expired.



17
18
19
20
21
22
23
24
25
# File 'lib/api_wrapper/cache/cache_store.rb', line 17

def fetch(key, ttl)
  if cached?(key, ttl)
    @store[key][:data]
  else
    fresh_data = yield
    store(key, fresh_data, ttl)
    fresh_data
  end
end

#read(key) ⇒ Object?

Reads data from the cache.

Parameters:

  • key (String)

    The cache key.

Returns:

  • (Object, nil)

    The cached data, or nil if not present.



31
32
33
# File 'lib/api_wrapper/cache/cache_store.rb', line 31

def read(key)
  cached?(key) ? @store[key][:data] : nil
end

#write(key, data, ttl) ⇒ Object

Writes data to the cache with an expiration time.

Parameters:

  • key (String)

    The cache key.

  • data (Object)

    The data to cache.

  • ttl (Integer)

    The time-to-live in seconds.



40
41
42
# File 'lib/api_wrapper/cache/cache_store.rb', line 40

def write(key, data, ttl)
  store(key, data, ttl)
end