Module: Pilipinas::Cache Private

Defined in:
lib/pilipinas/cache.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Thread-safe, process-lifetime in-memory cache.

YAML data files are large (42 k+ barangay records). Cache ensures each file is parsed exactly once per process and the result is reused for every subsequent look-up. Double-checked locking keeps mutex contention minimal in concurrent environments.

Examples:

value = Pilipinas::Cache.fetch("my_key") { expensive_computation }

Class Method Summary collapse

Class Method Details

.clearvoid

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Evict every cached entry.

Primarily useful between test examples to ensure isolation.



42
43
44
# File 'lib/pilipinas/cache.rb', line 42

def clear
  @mutex.synchronize { @store.clear }
end

.fetch(key) { ... } ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the cached value for key, computing it via block on the first invocation.

Parameters:

  • key (String)

    unique cache key

Yields:

  • called once, the return value is stored and returned

Returns:

  • (Object)

    the cached (or freshly computed) value



26
27
28
29
30
31
32
33
34
35
# File 'lib/pilipinas/cache.rb', line 26

def fetch(key)
  # Fast path: no locking when the key is already present.
  return @store[key] if @store.key?(key)

  @mutex.synchronize do
    # Second check inside the lock to prevent duplicate computation.
    @store[key] = yield unless @store.key?(key)
    @store[key]
  end
end

.keysArray<String>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a snapshot of all currently cached keys.

Returns:

  • (Array<String>)


49
50
51
# File 'lib/pilipinas/cache.rb', line 49

def keys
  @mutex.synchronize { @store.keys.dup }
end

.sizeInteger

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the number of cached entries.

Returns:

  • (Integer)


56
57
58
# File 'lib/pilipinas/cache.rb', line 56

def size
  @mutex.synchronize { @store.size }
end