Class: I8::Struct::Hash

Inherits:
Hash show all
Includes:
I8::Struct, NRSER::Props::Immutable::Hash
Defined in:
lib/nrser/labs/i8/struct/hash.rb

Overview

Base class for Hash-based “propertied” (NRSER::Props) structs created by new.

Constant Summary

Constants included from NRSER::Props::Immutable::Hash

NRSER::Props::Immutable::Hash::STORAGE

Class Method Summary collapse

Methods included from NRSER::Props::Immutable::Hash

included

Methods inherited from Hamster::Hash

#as_json, #to_mutable, #to_yaml

Methods included from NRSER::Ext::Tree

#each_branch, #leaves, #map_branches, #map_leaves, #map_tree

Class Method Details

.self.new(**prop_defs, &class_body) ⇒ Class<I8::Struct::Hash> .self.new(*args, **kwds, &block) ⇒ I8::Struct::Hash

This method does two totally different things depending on what ‘self` is:

  1. If ‘self` is I8::Struct::Hash, we want to build a new struct class.

  2. Otherwise, we want to defer up to ‘super` to create a new instance of `self`.

Overloads:



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/nrser/labs/i8/struct/hash.rb', line 92

def self.new *args, **kwds, &block
  # Are we {I8::Struct::Hash}? (See method doc).
  if self == I8::Struct::Hash
    # Yes, we are. Time to build a new struct class.
    
    # Make sure we weren't given an positional `args`.
    unless args.empty?
      raise NRSER::ArgumentError.new \
        "Can not supply positional args when building new",
        "{I8::Struct::Hash}",
        args: args,
        kwds: kwds
    end

    # Create the new subclass
    Class.new( I8::Struct::Hash ) do
      kwds.each do |name, value|
        prop_kwds = t.match value,
          t.type, ->( type ) {{ type: type }},
          t.hash_, value
        
        prop name, **prop_kwds
      end
      
      class_exec &block if block
    end

  else
    # No, we are a built struct. Defer up to `super` to create an instance.
    
    # NOTE  Weirdness ahead. See NOTE in {I8::Struct::Vector.new}
    if kwds.empty?
      super( *args, &block )
    else
      super( *args, **kwds, &block )
    end

  end
end