Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/couchdiff.rb

Overview

add “diff” method to Hash class. Exlude keys are used to exempt one or more keys (e.g. ‘_rev’)

Instance Method Summary collapse

Instance Method Details

#diff(other, keys_to_exclude = []) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/couchdiff.rb', line 6

def diff(other, keys_to_exclude = [])

  # check that values for all keys in this and other hash or the same
  result = ((self.keys - keys_to_exclude) + (other.keys - keys_to_exclude)).uniq.inject({}) do |memo, key|

    # if we have hashes on both sides...
    if self[key].kind_of?(Hash) && other[key].kind_of?(Hash)
      memo[key] = self[key].diff(other[key], keys_to_exclude)
    else
      # compare values directly (arrays or simple Strings, Numbers, Objects etc.)
      memo[key] = [self[key], other[key]] unless (self[key] == other[key])
    end
    # get rid of empty hashes
    memo.delete_if { |k, v| v.kind_of?(Hash) && v.empty? }
    memo
  end

  # Check that both hashes contain the same keys (in the same order)
  # uses special identifier "_keys_changed"
  result[:_keys_changed] = [self.keys, other.keys] if (self.keys != other.keys)
  result
end