Class: EmailDomainChecker::Cache::MemoryAdapter

Inherits:
BaseAdapter
  • Object
show all
Defined in:
lib/email_domain_checker/cache/memory_adapter.rb

Overview

In-memory cache adapter using a simple hash This is the default cache adapter when Redis is not available

Instance Method Summary collapse

Methods inherited from BaseAdapter

#with

Constructor Details

#initializeMemoryAdapter

Returns a new instance of MemoryAdapter.



10
11
12
13
14
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 10

def initialize
  @store = {}
  @expirations = {}
  @nil_keys = {} # Track keys that have nil values
end

Instance Method Details

#clearObject



56
57
58
59
60
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 56

def clear
  @store.clear
  @nil_keys.clear
  @expirations.clear
end

#delete(key) ⇒ Object



50
51
52
53
54
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 50

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

#exists?(key) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
72
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 62

def exists?(key)
  return false unless @store.key?(key) || @nil_keys.key?(key)

  # Check if expired
  if @expirations.key?(key) && Time.now > @expirations[key]
    delete(key)
    return false
  end

  true
end

#get(key) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 16

def get(key)
  # Check if key exists (including nil values)
  return nil unless @store.key?(key) || @nil_keys.key?(key)

  # Check if expired
  if @expirations.key?(key) && Time.now > @expirations[key]
    delete(key)
    return nil
  end

  # Return nil if it was explicitly cached, otherwise return stored value
  return nil if @nil_keys.key?(key)

  @store[key]
end

#set(key, value, ttl: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 32

def set(key, value, ttl: nil)
  if value.nil?
    # Store nil separately to distinguish from "not cached"
    @nil_keys[key] = true
    @store.delete(key)
  else
    @store[key] = value
    @nil_keys.delete(key)
  end

  if ttl
    @expirations[key] = Time.now + ttl
  else
    @expirations.delete(key)
  end
  value
end

#sizeObject

Get cache size (for debugging/monitoring)



75
76
77
78
79
# File 'lib/email_domain_checker/cache/memory_adapter.rb', line 75

def size
  # Clean expired entries first
  clean_expired
  @store.size + @nil_keys.size
end