Sha256: cef734fb9574d711f50cb65d54113a710d9e6b564e354e98d76fe7dcdd1b1fb6

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require 'attr/gather/aggregators/base'

module Attr
  module Gather
    module Aggregators
      # Deep merges result hashes
      #
      # @api public
      class DeepMerge < Base
        # Initialize a new DeepMerge aggregator
        #
        # @param reverse [Boolean] deep merge results in reverse order
        #
        # @api private
        def initialize(reverse: false, **)
          @reverse = reverse
          super
        end

        def call(input, execution_results)
          execution_results = execution_results.reverse_each if reverse?

          result = execution_results.reduce(input.dup) do |memo, res|
            deep_merge(memo, unwrap_result(res))
          end

          wrap_result(result)
        end

        private

        def reverse?
          @reverse
        end

        def deep_merge(hash, other)
          Hash[hash].merge(other) do |_, orig, new|
            if orig.respond_to?(:to_hash) && new.respond_to?(:to_hash)
              deep_merge(Hash[orig], Hash[new])
            else
              new
            end
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
attr-gather-1.1.0 lib/attr/gather/aggregators/deep_merge.rb
attr-gather-1.0.0 lib/attr/gather/aggregators/deep_merge.rb