Module: RailsBrotliCache

Defined in:
lib/rails-brotli-cache.rb,
lib/rails-brotli-cache/version.rb

Constant Summary collapse

COMPRESS_THRESHOLD =
ENV.fetch("BR_CACHE_COMPRESS_THRESHOLD", 1).to_f * 1024.0
COMPRESS_QUALITY =
ENV.fetch("BR_CACHE_COMPRESS_QUALITY", 5).to_i
MARK_BR_COMPRESSED =
"\x02".b
VERSION =
"0.1.1"
@@prefix =
"br-"

Class Method Summary collapse

Class Method Details

.cache_key(name) ⇒ Object



69
70
71
# File 'lib/rails-brotli-cache.rb', line 69

def self.cache_key(name)
  "#{@@prefix}#{name}"
end

.delete(name, options = nil) ⇒ Object



61
62
63
# File 'lib/rails-brotli-cache.rb', line 61

def self.delete(name, options = nil)
  Rails.cache.delete(cache_key(name), options)
end

.disable_prefix!Object



65
66
67
# File 'lib/rails-brotli-cache.rb', line 65

def self.disable_prefix!
  @@prefix = nil
end

.fetch(name, options = nil, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rails-brotli-cache.rb', line 12

def self.fetch(name, options = nil, &block)
  value = read(name, options)
  return value if value.present?

  if block_given?
    value = block.call
    write(name, value, options)

    value
  elsif options && options[:force]
    raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block."
  else
    read(name, options)
  end
end

.read(name, options = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rails-brotli-cache.rb', line 44

def self.read(name, options = nil)
  payload = Rails.cache.read(
    cache_key(name),
    options
  )

  return nil unless payload.present?

  serialized = if payload.start_with?(MARK_BR_COMPRESSED)
    ::Brotli.inflate(payload.byteslice(1..-1))
  else
    payload
  end

  Marshal.load(serialized)
end

.write(name, value, options = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rails-brotli-cache.rb', line 28

def self.write(name, value, options = nil)
  serialized = Marshal.dump(value)

  payload = if serialized.bytesize >= COMPRESS_THRESHOLD
    MARK_BR_COMPRESSED + ::Brotli.deflate(serialized, quality: COMPRESS_QUALITY)
  else
    serialized
  end

  Rails.cache.write(
    cache_key(name),
    payload,
    (options || {}).merge(compress: false)
  )
end