Class: Readthis::Entity
- Inherits:
-
Object
- Object
- Readthis::Entity
- 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
-
#compose(value, marshal, compress) ⇒ String
Composes a single byte comprised of the chosen serializer and compression options.
-
#decompose(string) ⇒ Array<Module, Boolean, String>
Decompose an option embedded string into marshal, compression and value.
-
#dump(value, options = {}) ⇒ String
Output a value prepared for cache storage.
-
#initialize(options = {}) ⇒ Entity
constructor
Creates a Readthis::Entity with default options.
-
#load(string) ⇒ String
Parse a dumped value using the embedded options.
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 = DEFAULT_OPTIONS.merge() 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.
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.
45 46 47 48 49 50 51 52 53 |
# File 'lib/readthis/entity.rb', line 45 def dump(value, = {}) compress = with_fallback(, :compress) marshal = with_fallback(, :marshal) threshold = with_fallback(, :threshold) dumped = deflate(marshal.dump(value), compress, threshold) compose(dumped, marshal, compress) end |
#load(string) ⇒ String
Parse a dumped value using the embedded options.
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 |