Module: JSONDiff
- Defined in:
- lib/json_diff.rb,
lib/json_diff/version.rb
Overview
Provides helper methods to compare object trees like those generated by JSON.parse and generate a diff list.
Defined Under Namespace
Modules: Version
Class Method Summary collapse
-
.arrays(a, b, path = '/') ⇒ Object
Assumes a and b are of class Array.
-
.objects(a, b, path = '') ⇒ Object
Assumes a and b are of class Hash.
Class Method Details
.arrays(a, b, path = '/') ⇒ Object
Assumes a and b are of class Array.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/json_diff.rb', line 36 def self.arrays(a, b, path='/') differences = [] if a.size != b.size differences << "size mismatch: #{path}" else a.zip(b).each_with_index do |pair, index| if pair[0].class != pair[1].class differences << "type mismatch: #{path}[#{index}] '#{pair[0].class}' != '#{pair[1].class}'" else if pair[0].is_a? Hash differences += objects(pair[0], pair[1], "#{path}[#{index}]") elsif pair[0].is_a? Array differences += arrays(pair[0], pair[1], "#{path}[#{index}]") elsif pair[0] != pair[1] # String, TrueClass, FalseClass, NilClass, Float, Fixnum differences << "value mismatch: #{path}[#{index}] '#{pair[0]}' != '#{pair[1]}'" end end end end differences end |
.objects(a, b, path = '') ⇒ Object
Assumes a and b are of class Hash.
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/json_diff.rb', line 7 def self.objects(a, b, path='') differences = [] a.each do |k, v| if b.has_key? k if v.class != b[k].class differences << "type mismatch: #{path}/#{k} '#{v.class}' != '#{b[k].class}'" else if v.is_a? Hash differences += objects(v, b[k], "#{path}/#{k}") elsif v.is_a? Array differences += arrays(v, b[k], "#{path}/#{k}") elsif v != b[k] # String, TrueClass, FalseClass, NilClass, Float, Fixnum differences << "value mismatch: #{path}/#{k} '#{v}' != '#{b[k]}'" end end else differences << "b is missing: #{path}/#{k}" end end (b.keys - a.keys).each do |k, v| differences << "a is missing: #{path}/#{k}" end differences end |