Class: Above::MiddleWare::Cache

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

Overview

Middleware for a naive cache that stores the last max_size worth of results in memory

Instance Method Summary collapse

Constructor Details

#initialize(app:) ⇒ Cache

Returns a new instance of Cache.



9
10
11
12
13
# File 'lib/above/middleware/cache.rb', line 9

def initialize(app:)
  @app = app # who you gonna call
  @cache = {}
  @max_size = nil
end

Instance Method Details

#call(env:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/above/middleware/cache.rb', line 15

def call(env:)
  # env is {socket:, request:, config:, valid:}

  # can't cache an invalid url
  return @app&.call(env:) unless env[:valid]

  if @max_size.nil?
    config = env[:config]["Above::MiddleWare::Cache"]
    @max_size = config["max_size"]
  end

  request = env[:request].to_s.chomp("/")
  if @cache.key?(request)
    # use the cached result if we have it
    @cache[request][:result]
  else
    # otherwise go on to find & cache the result
    result = @app.call(env:) unless @app.nil?

    # only keep the most recent @max_size worth of results
    if @cache.size >= @max_size
      oldest = @cache.min_by { |key, val| val[:time] }[0]
      @cache.delete(oldest)
    end
    @cache[request] = {
      result: result,
      time: Time.now
    }

    result
  end
end