Module: Paquito::Struct

Defined in:
lib/paquito/struct.rb

Overview

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:

  • defines a #values instance method

  • defines a .members class method

  • has an #initialize method that accepts the values as its arguments

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.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.digest(attr_names) ⇒ Object



56
57
58
# 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) ⇒ Object



37
38
39
40
41
42
# 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) ⇒ Object



50
51
52
53
54
# 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

Instance Method Details

#as_packObject



45
46
47
# File 'lib/paquito/struct.rb', line 45

def as_pack
  [self.class.pack_digest, *values]
end