Sha256: 760a21022d9efcd498c18337af05feac942e03319518003cdfd9a2adef01f9f7

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require "refinements/shared/diff"

module Refinements
  # Provides additional enhancements to the Struct primitive.
  module Struct
    refine ::Struct.singleton_class do
      def with_positions(*values)
        warn "`#{self.class}##{__method__}` is deprecated and will be removed in Version 13.0.0.",
             category: :deprecated

        keyword_init? ? new(**members.zip(values).to_h) : new(*values)
      end
    end

    refine ::Struct do
      import_methods Shared::Diff

      def merge(...) = dup.merge!(...)

      def merge! object = nil
        to_h.merge!(**object.to_h).each { |key, value| self[key] = value }
        self
      end

      def revalue attributes = each_pair
        return self unless block_given?

        dup.tap { |copy| attributes.each { |key, value| copy[key] = yield self[key], value } }
      end

      def revalue! attributes = each_pair
        return self unless block_given?

        attributes.each { |key, value| self[key] = yield self[key], value }
        self
      end

      def transmute(...) = dup.transmute!(...)

      def transmute! object, **key_map
        mapping = key_map.invert
        merge! object.to_h.slice(*mapping.keys).transform_keys!(mapping)
      end

      alias_method :with, :merge
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
refinements-12.11.0 lib/refinements/struct.rb
refinements-12.10.0 lib/refinements/struct.rb