Class: CacheLib::TtlCache

Inherits:
BasicCache show all
Defined in:
lib/cache_lib/ttl_cache.rb

Direct Known Subclasses

SafeTtlCache

Instance Attribute Summary

Attributes inherited from BasicCache

#limit

Instance Method Summary collapse

Methods inherited from BasicCache

#clear, #each, #key?, #keys, #size, #to_a, #values

Constructor Details

#initialize(*args) ⇒ TtlCache

Returns a new instance of TtlCache.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/cache_lib/ttl_cache.rb', line 3

def initialize(*args)
  limit, ttl = args

  fail ArgumentError, "Cache Limit must be 1 or greater: #{limit}" if
      limit.nil? || limit < 1
  fail ArgumentError, "TTL must be :none, 0 or greater: #{ttl}" unless
      ttl == :none || ((ttl.is_a? Numeric) && ttl >= 0)

  @limit = limit
  @ttl = ttl

  @cache = UtilHash.new
  @queue = UtilHash.new
end

Instance Method Details

#evict(key) ⇒ Object Also known as: delete



73
74
75
76
# File 'lib/cache_lib/ttl_cache.rb', line 73

def evict(key)
  @queue.delete(key)
  @cache.delete(key)
end

#expireObject



78
79
80
# File 'lib/cache_lib/ttl_cache.rb', line 78

def expire
  ttl_evict
end

#fetch(key) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/cache_lib/ttl_cache.rb', line 65

def fetch(key)
  if hit?(key)
    hit(key)
  else
    yield if block_given?
  end
end

#get(key) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/cache_lib/ttl_cache.rb', line 44

def get(key)
  if hit?(key)
    hit(key)
  else
    miss(key, yield)
  end
end

#initialize_copy(source) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/cache_lib/ttl_cache.rb', line 18

def initialize_copy(source)
  source_raw = source.raw

  @limit = source_raw[:limit]

  @cache = source_raw[:cache]
  @queue = source_raw[:queue]
end

#inspectObject



88
89
90
91
92
93
# File 'lib/cache_lib/ttl_cache.rb', line 88

def inspect
  "#{self.class}, "\
  "Limit: #{@limit}, "\
  "TTL: #{@ttl}, "\
  "Size: #{@cache.size}"
end

#limit=(args) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cache_lib/ttl_cache.rb', line 27

def limit=(args)
  limit, ttl = args

  limit ||= @limit
  ttl ||= @ttl

  fail ArgumentError, "Cache Limit must be 1 or greater: #{limit}" if
      limit.nil? || limit < 1
  fail ArgumentError, "TTL must be :none, 0 or greater: #{ttl}" unless
      ttl == :none || ((ttl.is_a? Numeric) && ttl >= 0)

  @limit = limit
  @ttl = ttl

  resize
end

#lookup(key) ⇒ Object Also known as: []



61
62
63
# File 'lib/cache_lib/ttl_cache.rb', line 61

def lookup(key)
  hit(key) if hit?(key)
end

#rawObject



82
83
84
85
86
# File 'lib/cache_lib/ttl_cache.rb', line 82

def raw
  { limit: @limit,
    cache: @cache.clone,
    queue: @queue.clone }
end

#store(key, value) ⇒ Object Also known as: []=



52
53
54
55
56
57
58
59
# File 'lib/cache_lib/ttl_cache.rb', line 52

def store(key, value)
  ttl_evict

  @cache.delete(key)
  @queue.delete(key)

  miss(key, value)
end