Module: Ooz::Common::HashDiff

Defined in:
lib/ooz/common/hash_diff.rb

Constant Summary collapse

ID_KEYS =
%w[_id]

Class Method Summary collapse

Class Method Details

.diff(a, b) ⇒ Object



6
7
8
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
# File 'lib/ooz/common/hash_diff.rb', line 6

def self.diff(a, b)
  return a if a.class != b.class
  case a
  when Hash
    {}.tap do |diffed|
      a.each do |key, a_value|
        b_value = b[key]
        next if a_value == b_value && !ID_KEYS.include?(key)
        diffed[key] = diff(a_value, b_value)
        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 a.length == b.length
    a.map.with_index do |a_value, idx|
      b_value = b[idx]
      diff(a_value, b_value)
    end.reject do |el|
      el == {}
    end
  else
    a
  end
end