Class: CacheHash

Inherits:
Object
  • Object
show all
Defined in:
lib/cache_hash.rb,
lib/cache_hash/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ttl: 60, gc_interval: 10) ⇒ CacheHash

Creates CacheHash and starts garbage collection



12
13
14
15
16
17
18
19
20
# File 'lib/cache_hash.rb', line 12

def initialize(ttl: 60, gc_interval: 10)
  @data = Hash.new
  @mutex = Mutex.new
  @gc_thread = nil

  @ttl  = ttl
  @gc_interval = gc_interval # seconds
  start_gc
end

Instance Attribute Details

#gc_intervalObject (readonly)

CacheHash is a simple hash implementation where the value is purged after TTL seconds.



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

def gc_interval
  @gc_interval
end

#ttlObject (readonly)

CacheHash is a simple hash implementation where the value is purged after TTL seconds.



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

def ttl
  @ttl
end

Instance Method Details

#[](key) ⇒ Object?

Gets value for key, or nil if expired



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cache_hash.rb', line 39

def [](key)
  @mutex.synchronize {
    if @data.has_key?(key)
      if Time.now.to_i > @data[key][:expires_at]
        # @data.delete(key)
        return nil
      else
        return @data[key][:value]
      end
    end
  }
  return nil
end

#[]=(key, value) ⇒ Object

Sets a value for a key and returns the value



26
27
28
29
30
31
32
33
34
# File 'lib/cache_hash.rb', line 26

def []=(key, value)
  @mutex.synchronize {
    @data[key] = {
      value: value,
      expires_at: Time.now.to_i + @ttl
    }
  }
  value
end

#fetch(key, default_value = nil) ⇒ Object?

Gets value for key, or default_value if expired

Raises:

  • (ArgumentError)


58
59
60
61
# File 'lib/cache_hash.rb', line 58

def fetch(key, default_value = nil)
  raise ArgumentError, "Block not given" if (block_given? && default_value)
  self[key] || default_value || (self[key] = yield) # (*args))
end

#gcObject

Delete keys with expired values



74
75
76
77
78
79
80
81
82
83
# File 'lib/cache_hash.rb', line 74

def gc
  now = Time.now.to_i
  @mutex.synchronize {
    @data.each_pair do |key, value|
      if now > @data[key][:expires_at]
        @data.delete key
      end
    end
  }
end

#start_gcObject

Kick off garbage collection in a thread



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

def start_gc
  @gc_thread = Thread.new do
    loop do
      sleep @gc_interval
      gc
    end
  end
end