Sha256: 3f4d739322eeeb3f855417b1df3e2d70e5d7e59bb6138266fa30a5fb0d7027d9

Contents?: true

Size: 1.79 KB

Versions: 9

Compression:

Stored size: 1.79 KB

Contents

# Copyright (c) 2023 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

module Contrast
  module Utils
    # Module to hold various hash utils methods
    module HashUtils
      class << self
        # Merges two hashes, first hash will preserve it's values and will only add unique values.
        #
        # @param hsh [Hash]
        # @param other_hsh [Hash]
        def precedence_merge hsh, other_hsh
          hsh.merge(other_hsh) do |_key, old_value, new_value|
            if old_value.is_a?(Hash) || new_value.is_a?(Hash)
              Contrast::Utils::HashUtils.precedence_merge(old_value, new_value)
            else
              old_value
            end
          end
        end

        # Merges two hashes, first hash will preserve it's values and will only add unique values.
        #
        # @param hsh [Hash]
        # @param other_hsh [Hash]
        # @return [Hash]
        def precedence_merge! hsh, other_hsh
          hsh.merge!(other_hsh) do |_key, old_val, new_val|
            if old_val.is_a?(Hash) || new_val.is_a?(Hash)
              Contrast::Utils::HashUtils.precedence_merge!(old_val, new_val)
            else
              old_val
            end
          end
        end

        # Deep symbolizes all keys
        # @param value [Hash]
        # @return [Hash]
        def deep_symbolize_all_keys value
          new_hash = {}
          value.each { |key, v| new_hash[key.to_sym] = map_value(v) }
          new_hash
        end

        private

        def map_value value
          case value
          when Hash
            deep_symbolize_all_keys(value)
          when Array
            value.map { |v| map_value(v) }
          else
            value
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
contrast-agent-7.6.1 lib/contrast/utils/hash_utils.rb
contrast-agent-7.6.0 lib/contrast/utils/hash_utils.rb
contrast-agent-7.5.0 lib/contrast/utils/hash_utils.rb
contrast-agent-7.4.1 lib/contrast/utils/hash_utils.rb
contrast-agent-7.4.0 lib/contrast/utils/hash_utils.rb
contrast-agent-7.3.2 lib/contrast/utils/hash_utils.rb
contrast-agent-7.3.1 lib/contrast/utils/hash_utils.rb
contrast-agent-7.3.0 lib/contrast/utils/hash_utils.rb
contrast-agent-7.2.0 lib/contrast/utils/hash_utils.rb