Class: Printavo::MemoryStore

Inherits:
Object
  • Object
show all
Defined in:
lib/printavo/memory_store.rb

Overview

A simple thread-safe in-memory cache store for use without Rails or Redis. Implements the same fetch / delete interface as Rails.cache, so it can be swapped for any compatible store without changing call sites.

Examples:

Standalone use

client = Printavo::Client.new(
  email: ENV["PRINTAVO_EMAIL"],
  token: ENV["PRINTAVO_TOKEN"],
  cache: Printavo::MemoryStore.new
)

With custom default TTL

client = Printavo::Client.new(
  email: ENV["PRINTAVO_EMAIL"],
  token: ENV["PRINTAVO_TOKEN"],
  cache:       Printavo::MemoryStore.new,
  default_ttl: 600  # 10 minutes
)

Instance Method Summary collapse

Constructor Details

#initializeMemoryStore

Returns a new instance of MemoryStore.



24
25
26
27
28
# File 'lib/printavo/memory_store.rb', line 24

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

Instance Method Details

#delete(key) ⇒ nil

Removes key from the cache.

Parameters:

  • key (String)

Returns:

  • (nil)


50
51
52
53
54
55
56
# File 'lib/printavo/memory_store.rb', line 50

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

#fetch(key, expires_in: nil) ⇒ Object

Returns the cached value for key, or calls the block, stores the result, and returns it. Expired entries are treated as missing.

Parameters:

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

    TTL in seconds; nil means no expiry

Yield Returns:

  • the value to cache on a miss

Returns:

  • the cached or freshly-computed value



37
38
39
40
41
42
43
44
# File 'lib/printavo/memory_store.rb', line 37

def fetch(key, expires_in: nil)
  @mutex.synchronize do
    cached = read(key)
    return cached unless cached.nil?

    yield.tap { |v| write(key, v, expires_in: expires_in) }
  end
end