Class: Upgrow::ImmutableStruct

Inherits:
Struct
  • Object
show all
Defined in:
lib/upgrow/immutable_struct.rb

Overview

A read-only Struct. An Immutable Struct is initialized with its member values and subsequent state changes are not permitted.

Direct Known Subclasses

Result

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**args) ⇒ ImmutableStruct

Initializes a new Immutable Struct with the given member values.

Parameters:

  • args (Hash<Symbol, Object>)

    the list of values for each member of the Immutable Struct.



35
36
37
38
39
# File 'lib/upgrow/immutable_struct.rb', line 35

def initialize(**args)
  members.each { |key| args.fetch(key) }
  super(**args)
  freeze
end

Class Method Details

.new(*args, &block) ⇒ ImmutableStruct

Creates a new Immutable Struct class with the given members.

Parameters:

  • args (Array<Symbol>)

    the list of members for the new class.

Returns:

  • (ImmutableStruct)

    the new Immutable Struct class able to accommodate the given members.



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/upgrow/immutable_struct.rb', line 14

def new(*args, &block)
  if args.any? { |member| !member.is_a?(Symbol) }
    raise ArgumentError, 'all members must be symbols'
  end

  struct_class = super(*args, keyword_init: true, &block)

  struct_class.members.each do |member|
    struct_class.send(:undef_method, :"#{member}=")
  end

  struct_class
end