Class: Relay::Cache::InMemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/relay/cache/in_memory_cache.rb

Overview

A small in-process cache that supports dynamic attribute-style access.

Missing keys are initialized as nested InMemoryCache instances, which makes it convenient for lightweight grouped state such as cached model lists or provider-specific values.

Instance Method Summary collapse

Constructor Details

#initializeRelay::Cache::InMemoryCache



13
14
15
# File 'lib/relay/cache/in_memory_cache.rb', line 13

def initialize
  @cache = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object

Handles dynamic cache reads and writes.

Setter calls like ‘cache.models = value` store the value under the corresponding string key. Getter calls return the stored value when present, or initialize a nested InMemoryCache when missing.

Parameters:

  • m (Symbol)
  • args (Array)

Returns:

  • (Object)


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

def method_missing(m, *args, &block)
  if m.to_s.end_with?("=")
    self[m.to_s[0..-2]] = args[0]
  elsif @cache.key?(m.to_s)
    @cache[m.to_s]
  else
    @cache[m.to_s] = InMemoryCache.new
  end
end

Instance Method Details

#[](k) ⇒ Object?

Fetches a value by key.

Parameters:

  • k (String, Symbol)

Returns:

  • (Object, nil)


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

def [](k)
  @cache[k.to_s]
end

#[]=(k, v) ⇒ Object

Stores a value by key.

Parameters:

  • k (String, Symbol)
  • v (Object)

Returns:

  • (Object)


48
49
50
# File 'lib/relay/cache/in_memory_cache.rb', line 48

def []=(k, v)
  @cache[k.to_s] = v
end

#respond_to_missing?(m, include_private = false) ⇒ Boolean

Respond to missing methods that are handled by method_missing.

Returns:

  • (Boolean)


39
40
41
# File 'lib/relay/cache/in_memory_cache.rb', line 39

def respond_to_missing?(m, include_private = false)
  true
end