Class: ActiveSupport::Cache::Coder

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/cache/coder.rb

Overview

:nodoc:

Defined Under Namespace

Classes: LazyEntry, StringDeserializer

Instance Method Summary collapse

Constructor Details

#initialize(serializer, compressor, legacy_serializer: false) ⇒ Coder

Returns a new instance of Coder.



8
9
10
11
12
# File 'lib/active_support/cache/coder.rb', line 8

def initialize(serializer, compressor, legacy_serializer: false)
  @serializer = serializer
  @compressor = compressor
  @legacy_serializer = legacy_serializer
end

Instance Method Details

#dump(entry) ⇒ Object



14
15
16
17
18
# File 'lib/active_support/cache/coder.rb', line 14

def dump(entry)
  return @serializer.dump(entry) if @legacy_serializer

  dump_compressed(entry, Float::INFINITY)
end

#dump_compressed(entry, threshold) ⇒ Object



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/active_support/cache/coder.rb', line 20

def dump_compressed(entry, threshold)
  return @serializer.dump_compressed(entry, threshold) if @legacy_serializer

  # If value is a string with a supported encoding, use it as the payload
  # instead of passing it through the serializer.
  if type = type_for_string(entry.value)
    payload = entry.value.b
  else
    type = OBJECT_DUMP_TYPE
    payload = @serializer.dump(entry.value)
  end

  if compressed = try_compress(payload, threshold)
    payload = compressed
    type = type | COMPRESSED_FLAG
  end

  expires_at = entry.expires_at || -1.0

  version = dump_version(entry.version) if entry.version
  version_length = version&.bytesize || -1

  packed = SIGNATURE.b
  packed << [type, expires_at, version_length].pack(PACKED_TEMPLATE)
  packed << version if version
  packed << payload
end

#load(dumped) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/active_support/cache/coder.rb', line 48

def load(dumped)
  return @serializer.load(dumped) if !signature?(dumped)

  type = dumped.unpack1(PACKED_TYPE_TEMPLATE)
  expires_at = dumped.unpack1(PACKED_EXPIRES_AT_TEMPLATE)
  version_length = dumped.unpack1(PACKED_VERSION_LENGTH_TEMPLATE)

  expires_at = nil if expires_at < 0
  version = load_version(dumped.byteslice(PACKED_VERSION_INDEX, version_length)) if version_length >= 0
  payload = dumped.byteslice((PACKED_VERSION_INDEX + [version_length, 0].max)..)

  compressor = @compressor if type & COMPRESSED_FLAG > 0
  serializer = STRING_DESERIALIZERS[type & ~COMPRESSED_FLAG] || @serializer

  LazyEntry.new(serializer, compressor, payload, version: version, expires_at: expires_at)
end