Sha256: e7f4beaaf8a451699ca41e5a09b144cc56fa8a630f7f18fe833bc5a994bc2e8d

Contents?: true

Size: 962 Bytes

Versions: 3

Compression:

Stored size: 962 Bytes

Contents

# frozen_string_literal: true

module Refinements
  module Structs
    refine Struct.singleton_class do
      def keyworded? = inspect.include?("keyword_init: true")

      def with_keywords(**arguments) = keyworded? ? new(**arguments) : new.merge!(**arguments)

      def with_positions(*values) = keyworded? ? new(**members.zip(values).to_h) : new(*values)
    end

    refine Struct do
      def merge(**attributes) = dup.merge!(**attributes)

      def merge! **attributes
        to_h.merge(**attributes).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
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
refinements-8.2.2 lib/refinements/structs.rb
refinements-8.2.1 lib/refinements/structs.rb
refinements-8.2.0 lib/refinements/structs.rb