Sha256: b7f70e6c90b06a66de99f5a4608699524a0819efccb97d3e93ed4eed961df6e8

Contents?: true

Size: 1.14 KB

Versions: 4

Compression:

Stored size: 1.14 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) = keyword_init? ? new(**members.zip(values).to_h) : new(*values)
    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

4 entries across 4 versions & 1 rubygems

Version Path
refinements-12.9.0 lib/refinements/struct.rb
refinements-12.8.0 lib/refinements/struct.rb
refinements-12.7.1 lib/refinements/struct.rb
refinements-12.7.0 lib/refinements/struct.rb