Sha256: 7349c7219617b9d6f6831cac38b6f4138da47a98be5346dce93e3f306d33b978

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true
module Upgrow
  # A read-only Struct. An Immutable Struct is initialized with its member
  # values and subsequent state changes are not permitted.
  class ImmutableStruct < Struct
    class << self
      # Creates a new Immutable Struct class with the given members.
      #
      # @param args [Array<Symbol>] the list of members for the new class.
      #
      # @return [ImmutableStruct] the new Immutable Struct class able to
      #   accommodate the given members.
      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
    end

    undef []=

    # Initializes a new Immutable Struct with the given member values.
    #
    # @param args [Hash<Symbol, Object>] the list of values for each member of
    #   the Immutable Struct.
    def initialize(**args)
      members.each { |key| args.fetch(key) }
      super(**args)
      freeze
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
upgrow-0.0.3 lib/upgrow/immutable_struct.rb
upgrow-0.0.2 lib/upgrow/immutable_struct.rb