Class: DiffJson::Diff

Inherits:
Object
  • Object
show all
Includes:
JsonDiffing, JsonMapping
Defined in:
lib/diff_json/diff.rb

Instance Method Summary collapse

Constructor Details

#initialize(old_json, new_json, **opts) ⇒ Diff



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/diff_json/diff.rb', line 29

def initialize(old_json, new_json, **opts)
  # Set config options
  @opts = {
    count_operations: {
      '/**' => [:add, :replace, :remove, :move, :update]
    },
    ignore_paths: [],
    path_sort: :sorted,
    sub_diffs: {},
    track_array_moves: true,
    track_structure_updates: false,
    replace_primitives_arrays: false,
    logger: ::Logger.new(STDOUT),
    log_level: :warn
  }.merge(opts)
  # Create map of both JSON objects
  @old_map = map_json(old_json, '', 0)
  @new_map = map_json(new_json, '', 0)
  # Gather the full list of all paths in both JSON objects in a consistent order
  @all_paths = gather_paths(@old_map.keys, @new_map.keys, @opts[:path_sort] == :sorted)
  # Generate diff operations list
  @diff = diff_check(old_json, new_json)
  # Find difference counts
  @counts = find_counts(@diff)
  # Gather sub-diffs
  @sub_diffs = generate_sub_diffs
end

Instance Method Details

#count(count_type = :all) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/diff_json/diff.rb', line 57

def count(count_type = :all)
  return case count_type
  when :ignore, :add, :replace, :remove, :move, :update
    @counts[count_type] || 0
  when :total
    @counts.values.sum
  else
    @counts
  end
end

#diffObject



68
69
70
# File 'lib/diff_json/diff.rb', line 68

def diff
  return @diff
end

#json_map(version = :old) ⇒ Object



72
73
74
# File 'lib/diff_json/diff.rb', line 72

def json_map(version = :old)
  return (version == :old ? @old_map : @new_map)
end

#log_message(log_level, message) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/diff_json/diff.rb', line 91

def log_message(log_level, message)
  log_levels = [
    :debug,
    :info,
    :warn,
    :error
  ]

  if (log_levels.index(log_level) || -1) >= (log_levels.index(@opts[:log_level]) || 0)
    @opts[:logger].method(log_level).call((is_structure?(message) ? JSON.pretty_generate(message) : message))
  end
end

#paths(version = :joint) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/diff_json/diff.rb', line 76

def paths(version = :joint)
  return case version
  when :old
    json_map(:old).keys
  when :new
    json_map(:new).keys
  else
    @all_paths
  end
end

#sub_diffsObject



87
88
89
# File 'lib/diff_json/diff.rb', line 87

def sub_diffs
  return @sub_diffs
end