Class: Cream::Cache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration_seconds) ⇒ Cache

Returns a new instance of Cache.



7
8
9
10
# File 'lib/cream/cache.rb', line 7

def initialize(duration_seconds)
  @duration_seconds = duration_seconds
  @items = {}
end

Instance Attribute Details

#duration_secondsObject (readonly)

Returns the value of attribute duration_seconds.



5
6
7
# File 'lib/cream/cache.rb', line 5

def duration_seconds
  @duration_seconds
end

#itemsObject (readonly)

Returns the value of attribute items.



5
6
7
# File 'lib/cream/cache.rb', line 5

def items
  @items
end

Instance Method Details

#get(key) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/cream/cache.rb', line 18

def get(key)
  item = items[key]

  if item&.expired?
    items.delete(key)
    return nil
  end

  item&.value
end

#set(key, value) ⇒ Object



12
13
14
15
16
# File 'lib/cream/cache.rb', line 12

def set(key, value)
  expires_at = Time.now + duration_seconds
  item = Cream::CacheItem.new(value, expires_at)
  items.merge!(Hash[key, item])
end