Class: Rack::SmartCompress::LruCache

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/rack/smart_compress/lru_cache.rb

Constant Summary collapse

DEFAULT_MAX_SIZE =
200

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ LruCache

Returns a new instance of LruCache.



15
16
17
18
19
20
21
# File 'lib/rack/smart_compress/lru_cache.rb', line 15

def initialize(max_size = DEFAULT_MAX_SIZE)
  super()
  @max_size = max_size
  @cache = {}
  @hits = 0
  @misses = 0
end

Instance Attribute Details

#hitsObject (readonly)

Returns the value of attribute hits.



13
14
15
# File 'lib/rack/smart_compress/lru_cache.rb', line 13

def hits
  @hits
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



13
14
15
# File 'lib/rack/smart_compress/lru_cache.rb', line 13

def max_size
  @max_size
end

#missesObject (readonly)

Returns the value of attribute misses.



13
14
15
# File 'lib/rack/smart_compress/lru_cache.rb', line 13

def misses
  @misses
end

Instance Method Details

#build_key(encoder_name, level, content) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/rack/smart_compress/lru_cache.rb', line 76

def build_key(encoder_name, level, content)
  digest = Digest::SHA256.new
  digest.update(encoder_name.to_s)
  digest.update(":")
  digest.update(level.to_s)
  digest.update(":")
  digest.update(content.to_s)
  digest.hexdigest
end

#clearObject



64
65
66
67
68
69
70
# File 'lib/rack/smart_compress/lru_cache.rb', line 64

def clear
  mon_synchronize do
    @cache.clear
    @hits = 0
    @misses = 0
  end
end

#delete(key) ⇒ Object



60
61
62
# File 'lib/rack/smart_compress/lru_cache.rb', line 60

def delete(key)
  mon_synchronize { @cache.delete(key) }
end

#fetch(key) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/rack/smart_compress/lru_cache.rb', line 37

def fetch(key)
  cached = get(key)
  return cached unless cached.nil?
  return nil unless block_given?

  # Execute expensive compression outside the mutex lock
  value = yield
  put(key, value)
  value
end

#get(key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/smart_compress/lru_cache.rb', line 23

def get(key)
  mon_synchronize do
    if @cache.key?(key)
      @hits += 1
      value = @cache.delete(key)
      @cache[key] = value # Move to end (MRU)
      value
    else
      @misses += 1
      nil
    end
  end
end

#put(key, value) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rack/smart_compress/lru_cache.rb', line 48

def put(key, value)
  mon_synchronize do
    @cache.delete(key)
    @cache[key] = value

    if @cache.size > @max_size
      @cache.shift # Remove oldest (LRU)
    end
    value
  end
end

#sizeObject



72
73
74
# File 'lib/rack/smart_compress/lru_cache.rb', line 72

def size
  mon_synchronize { @cache.size }
end