Sha256: 7c050be46c53bd4cb4733ff2e9cf4c3a755fecaab49b113f6a79f28159b21dcd

Contents?: true

Size: 944 Bytes

Versions: 1

Compression:

Stored size: 944 Bytes

Contents

# frozen_string_literal: true

require_relative 'struct/version'

module Micro
  module Struct
    def self.new(*keys, &block)
      struct = ::Struct.new(*keys, &block)

      struct.send(:private_class_method, :new)
      struct.send(:alias_method, :to_ary, :to_a)
      struct.send(:alias_method, :to_hash, :to_h)

      mod = Module.new
      mod.const_set(:Struct, struct)

      # The .new() method will require all of the Struct's keyword arguments.
      # We are doing this because Struct's keyword_init option doesn't do that.
      mod.module_eval(<<~RUBY, __FILE__, __LINE__ + 1)    #
        def self.new(#{struct.members.join(':, ')}:)      # def self.new(a:, b:) do
          Struct.send(:new, #{struct.members.join(', ')}) #   Struct.send(:new, a, b)
        end                                               # end

        def self.to_proc
          ->(hash) { new(**hash) }
        end
      RUBY

      mod
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
u-struct-0.3.1 lib/micro/struct.rb