Sha256: 4575f86d7ee90df576c1e1522691c2c66741b3f611c814026a5d75b4bfd58684

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 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
        # @param merge_input [Boolean] include input in aggregation result
        #
        # @api private
        def initialize(reverse: false, merge_input: true, **)
          @reverse = reverse
          @merge_input = merge_input
          super
        end

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

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

          wrap_result(result)
        end

        private

        def unwrap_initial_input(input)
          merge_input? ? filter.call(input.dup).value : {}
        end

        def reverse?
          @reverse
        end

        def merge_input?
          @merge_input
        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.3 lib/attr/gather/aggregators/deep_merge.rb
attr-gather-1.1.2 lib/attr/gather/aggregators/deep_merge.rb