Class: Justifi::InMemoryCache

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

Constant Summary collapse

HALF_DAY_IN_SECONDS =
43200

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInMemoryCache

Returns a new instance of InMemoryCache.



7
8
9
# File 'lib/justifi/in_memory_cache.rb', line 7

def initialize
  @data = {}
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



3
4
5
# File 'lib/justifi/in_memory_cache.rb', line 3

def data
  @data
end

Instance Method Details

#clear_cacheObject



50
51
52
# File 'lib/justifi/in_memory_cache.rb', line 50

def clear_cache
  @data = {}
end

#expirable_value(value, expiration) ⇒ Object



28
29
30
# File 'lib/justifi/in_memory_cache.rb', line 28

def expirable_value(value, expiration)
  {value: value, expiration: expiration}
end

#expire_key!(key) ⇒ Object



46
47
48
# File 'lib/justifi/in_memory_cache.rb', line 46

def expire_key!(key)
  @data.delete(key.to_s)
end

#expired?(expiration) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/justifi/in_memory_cache.rb', line 42

def expired?(expiration)
  !expiration.nil? && Time.now > expiration
end

#get(key) ⇒ Object



32
33
34
35
# File 'lib/justifi/in_memory_cache.rb', line 32

def get(key)
  expire_key!(key) if expired?(@data[key.to_s]&.fetch(:expiration))
  @data[key.to_s]&.fetch(:value)
end

#get_expiration(key) ⇒ Object



37
38
39
40
# File 'lib/justifi/in_memory_cache.rb', line 37

def get_expiration(key)
  expire_key!(key) if expired?(@data[key.to_s]&.fetch(:expiration))
  @data[key.to_s]&.fetch(:expiration)
end

#init(data) ⇒ Object

preload data into the cache



12
13
14
15
16
# File 'lib/justifi/in_memory_cache.rb', line 12

def init(data)
  data.map do |key, value|
    set(key, value)
  end
end

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



18
19
20
21
# File 'lib/justifi/in_memory_cache.rb', line 18

def set(key, value, expiration: nil)
  expiration ||= Time.now + HALF_DAY_IN_SECONDS
  @data[key.to_s] = expirable_value(value, expiration)
end

#set_and_return(key, value, expiration: nil) ⇒ Object



23
24
25
26
# File 'lib/justifi/in_memory_cache.rb', line 23

def set_and_return(key, value, expiration: nil)
  set(key, value, expiration: expiration)
  value
end