Module: Farce::MessagePack

Extended by:
MessagePack
Included in:
MessagePack
Defined in:
lib/farce/integrations/msgpack.rb

Overview

Note:

This module is only available if MessagePack has been loaded.

ActiveSupport Integration collapse

DEFAULT_TYPES =

Default mapping used by factory.

{ Vector => 0, Map => 1, Counter => 2, Flag => 3, Atom => 4, Set => 5 }.freeze

ActiveSupport Integration collapse

Class Method Details

.factory(types: DEFAULT_TYPES) ⇒ ::MessagePack::Factory

Note:

This method is only available if MessagePack has been loaded.

Build a factory that restores registered Farce classes. Use the same type IDs when writing and reading data.

Parameters:

  • types (Hash{Class => Integer}) (defaults to: DEFAULT_TYPES) —

    Classes and their application extension IDs.

Returns:

  • (::MessagePack::Factory) —

    An independent factory.



59
60
61
62
63
# File 'lib/farce/integrations/msgpack.rb', line 59

def factory(types: DEFAULT_TYPES)
  result = ::MessagePack::Factory.new
  types.each { |klass, type| register_type(result, type, klass) }
  result
end

.register_type(factory, type, klass) ⇒ ::MessagePack::Factory

Note:

This method is only available if MessagePack has been loaded.

Register a Farce class on an application-owned factory. Values use the same factory recursively, including nested custom types. Source configuration is replaced by the supplied constructor options. Counters also retain their initial value for reset.

Parameters:

  • factory (::MessagePack::Factory) —

    The factory to configure.

  • type (Integer) —

    An unused application extension ID from 0 through 127.

  • klass (Class) —

    A concrete Farce vector, map, set, counter, flag, or atom class.

  • options (Hash{Symbol => Object}) —

    Constructor options for restored objects.

Returns:

  • (::MessagePack::Factory) —

    The supplied factory.

Raises:

  • (ArgumentError) —

    If the class is unsupported or the ID or class is already registered.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/farce/integrations/msgpack.rb', line 77

def register_type(factory, type, klass, **)
  reader = primitive_reader(klass)
  unless type.is_a?(Integer) && (0..127).cover?(type)
    raise ArgumentError, "MessagePack extension IDs must be integers from 0 through 127"
  end
  if factory.registered_types.any? { it[:type] == type || it[:class] == klass }
    raise ArgumentError, "MessagePack extension ID or class is already registered"
  end

  counter = klass <= Abstract::Counter
  factory.register_type(type, klass,
    packer:    lambda { |object, packer|
      packer.write(object.initial) if counter
      packer.write(object.public_send(reader))
    },
    unpacker:  lambda { |unpacker|
      object = klass.new(unpacker.read, **)
      object.value = unpacker.read if counter
      object
    },
    recursive: true)
  factory
end