module Paquito::Struct

To make a Struct class cacheable, include Paquito::Struct:

MyStruct = Struct.new(:foo, :bar)
MyStruct.include(Paquito::Struct)

Alternatively, declare the struct with Paquito::Struct#new:

MyStruct = Paquito::Struct.new(:foo, :bar)

The struct defines as_pack and .from_pack methods:

my_struct = MyStruct.new("foo", "bar")
my_struct.as_pack
=> [26450, "foo", "bar"]

MyStruct.from_pack([26450, "foo", "bar"])
=> #<struct FooStruct foo="foo", bar="bar">

The Paquito::Struct module can be used in non-Struct classes, so long as the class:

If the last condition is not met, you can override .from_pack on the class and initialize the instance however you like, optionally using the private extract_packed_values method to extract values from the payload.

Public Class Methods

digest(attr_names) click to toggle source
# File lib/paquito/struct.rb, line 56
def digest(attr_names)
  ::Digest::MD5.digest(attr_names.map(&:to_s).join(",")).unpack1("s")
end
included(base) click to toggle source
# File lib/paquito/struct.rb, line 37
def included(base)
  base.class_eval do
    @__kw_init__ = inspect.include?("keyword_init: true")
  end
  base.extend(ClassMethods)
end
new(*members, keyword_init: false, &block) click to toggle source
# File lib/paquito/struct.rb, line 50
def new(*members, keyword_init: false, &block)
  struct = ::Struct.new(*members, keyword_init: keyword_init, &block)
  struct.include(Paquito::Struct)
  struct
end

Public Instance Methods

as_pack() click to toggle source
# File lib/paquito/struct.rb, line 45
def as_pack
  [self.class.pack_digest, *values]
end