module Reading::Util::DeeperMerge

modified from active_support/core_ext/hash/deeper_merge

Public Instance Methods

deeper_merge(other_hash, &block) click to toggle source
# File lib/reading/util.rb, line 33
def deeper_merge(other_hash, &block)
  dup.deeper_merge!(other_hash, &block)
end
deeper_merge!(other_hash, &block) click to toggle source
# File lib/reading/util.rb, line 37
def deeper_merge!(other_hash, &block)
  merge!(other_hash) do |key, this_val, other_val|
    if this_val.is_a?(Hash) && other_val.is_a?(Hash)
      this_val.deeper_merge(other_val, &block)
    # I added this part for merging values that are arrays of hashes.
    elsif this_val.is_a?(Array) && other_val.is_a?(Array) &&
          this_val.all? { |el| el.is_a?(Hash) } &&
          other_val.all? { |el| el.is_a?(Hash) }
      zip = if other_val.length >= this_val.length
              other_val.zip(this_val)
            else
              this_val.zip(other_val).map(&:reverse)
            end
      zip.map do |other_el, this_el|
        if this_el.nil?
          other_el
        else
          this_el.deeper_merge(other_el || {})
        end
      end
    elsif block_given?
      block.call(key, this_val, other_val)
    else
      other_val
    end
  end
end