lib/phlex/fifo_cache_store.rb
Lines
65%15 of 23 covered
Branches
40%4 of 10 covered
Methods
75%3 of 4 covered
- Not run
- 28-293741-4446
- Never called
| 1 | # frozen_string_literal: true | |
| 2 | ||
| 3 | # An extremely fast in-memory cache store that evicts keys on a first-in-first-out basis. | |
| 4 | 1 | class Phlex::FIFOCacheStore |
| 5 | 1 | def initialize(max_bytesize: 2 ** 20) |
| 6 | 79 | @fifo = Phlex::FIFO.new( |
| 7 | max_bytesize:, | |
| 8 | max_value_bytesize: max_bytesize | |
| 9 | ) | |
| 10 | end | |
| 11 | ||
| 12 | # Options such as `expires_in:` are accepted for compatibility with `Rails.cache` but ignored. | |
| 13 | 1 | def fetch(key, **) |
| 14 | 235 | fifo = @fifo |
| 15 | 235 | key = map_key(key) |
| 16 | ||
| 17 | 235 | if (result = fifo[key]) |
| 18 | 119 | Marshal.load(result) |
| 19 | else | |
| 20 | 116 | result = yield |
| 21 | ||
| 22 | 114 | fifo[key] = Marshal.dump(result) |
| 23 | ||
| 24 | 114 | result |
| 25 | end | |
| 26 | end | |
| 27 | ||
| 28 | 0 | def clear |
| 29 | 0 | @fifo.clear |
| 30 | end | |
| 31 | ||
| 32 | 1 | private def map_key(value) |
| 33 | 545 | case value |
| 34 | when Array | |
| 35 | 417 | value.map { |it| map_key(it) } |
| 36 | when Hash | |
| 37 | 0 | value.to_h { |k, v| [map_key(k), map_key(v)].freeze }when never taken |
| 38 | when String, Symbol, Integer, Float, Time, true, false, nil | |
| 39 | 438 | value |
| 40 | else | |
| 41 | 0 | if value.respond_to?(:cache_key_with_version)else never taken |
| 42 | 0 | map_key(value.cache_key_with_version) |
| 43 | 0 | elsif value.respond_to?(:cache_key) |
| 44 | 0 | map_key(value.cache_key) |
| 45 | else | |
| 46 | 0 | raise ArgumentError.new("Invalid cache key: #{value.class}") |
| 47 | end | |
| 48 | end | |
| 49 | end | |
| 50 | end |