Module: Ecoportal::API::Common::HashDiff

Defined in:
lib/ecoportal/api/common/hash_diff.rb

Constant Summary collapse

ID_KEYS =
%w[id]

Class Method Summary collapse

Class Method Details

.diff(a, b, ignore: []) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ecoportal/api/common/hash_diff.rb', line 9

def diff(a, b, ignore: [])
  case a
  when Hash
    {}.tap do |diffed|
      a.each do |key, a_value|
        b_value    = b && b[key]
        no_changes = (a_value == b_value) || ignore.include?(key)
        next if !ID_KEYS.include?(key) && no_changes
        diffed[key] = diff(a_value, b_value, ignore: ignore)
        diffed.delete(key) if diffed[key] == {}
      end
      # All keys are IDs, so it's actually blank
      if (diffed.keys - ID_KEYS).empty?
        return {}
      end
    end
  when Array
    return a unless b.is_a?(Array) && a.length == b.length
    a.map.with_index do |a_value, idx|
      b_value = b[idx]
      diff(a_value, b_value, ignore: ignore)
    end.reject do |el|
      el == {}
    end
  else
    a
  end
end