Class: Readthis::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/readthis/entity.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  compress:  false,
  marshal:   Marshal,
  threshold: 8 * 1024
}.freeze
COMPRESSED_FLAG =
0x8

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Entity

Creates a Readthis::Entity with default options. Each option can be overridden later when entities are being dumped.

Options are sticky, meaning that whatever is used when dumping will automatically be used again when loading, regardless of how current options are set.



24
25
26
# File 'lib/readthis/entity.rb', line 24

def initialize(options = {})
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Method Details

#compose(value, marshal, compress) ⇒ String

Composes a single byte comprised of the chosen serializer and compression options. The byte is formatted as:

| 0000 | 0 | 000 |

Where there are four unused bits, 1 compression bit, and 3 bits for the serializer. This allows up to 8 different serializers for marshaling.

Examples:

Compose an option embedded string


entity.compose(string, Marshal, false) => 0x1  + string
entity.compose(string, JSON, true)     => 0x10 + string


90
91
92
93
94
95
# File 'lib/readthis/entity.rb', line 90

def compose(value, marshal, compress)
  flags  = serializers.assoc(marshal)
  flags |= COMPRESSED_FLAG if compress

  value.prepend([flags].pack('C'))
end

#decompose(string) ⇒ Array<Module, Boolean, String>

Decompose an option embedded string into marshal, compression and value.



103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/readthis/entity.rb', line 103

def decompose(string)
  flags = string[0].unpack('C').first

  if flags < 16
    marshal  = serializers.rassoc(flags)
    compress = (flags & COMPRESSED_FLAG) != 0

    [marshal, compress, string[1..-1]]
  else
    [@options[:marshal], @options[:compress], string]
  end
end

#dump(value, options = {}) ⇒ String

Output a value prepared for cache storage. Passed options will override whatever has been specified for the instance.

Examples:

Dumping a value using defaults


entity.dump(string)

Dumping a value with overrides


entity.dump(string, compress: false, marshal: JSON)


45
46
47
48
49
50
51
52
53
# File 'lib/readthis/entity.rb', line 45

def dump(value, options = {})
  compress  = with_fallback(options, :compress)
  marshal   = with_fallback(options, :marshal)
  threshold = with_fallback(options, :threshold)

  dumped = deflate(marshal.dump(value), compress, threshold)

  compose(dumped, marshal, compress)
end

#load(string) ⇒ String

Parse a dumped value using the embedded options.

Examples:


entity.load(dumped)


64
65
66
67
68
69
70
# File 'lib/readthis/entity.rb', line 64

def load(string)
  marshal, compress, value = decompose(string)

  marshal.load(inflate(value, compress))
rescue TypeError, NoMethodError
  string
end