Class: HashDeepDiff::Delta

Inherits:
Object
  • Object
show all
Includes:
ActsAsHash
Defined in:
lib/hash_deep_diff/delta.rb

Overview

Representation of the diff of two values examples:

- diff of { a: a } and {} is { a: { left: a, right: HashDeepDiff::NO_VALUE } }
- diff of { a: a } and { a: b } is { a: { left: a, right: b } }
- diff of {} and { a: b } is { a: { left: HashDeepDiff::NO_VALUE, right: b } }

Instance Method Summary collapse

Methods included from ActsAsHash

included

Constructor Details

#initialize(path:, value:) ⇒ Delta (private)

Returns a new instance of Delta.

Parameters:

  • path (Array, Object)

    list of keys to fetch values we’re comparing

  • value (Hash<(:left, :right), Object>)

    Hash object with two keys - :left and :right, that represents compared original value (at :left) and value we compare to (at :right)



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/hash_deep_diff/delta.rb', line 53

def initialize(path:, value:)
  # TOFIX this may prohibit usage of hashes with Array keys
  # TOFIX extract path to a separate object
  if path.respond_to?(:to_ary)
    @delta = { path[-1] => value }
    @value = value
    @prefix = path[0..-2]
  else
    @delta = { path => value }
    @value = value
    @prefix = []
  end
end

Instance Method Details

#additionNillClass, String (private)

Visual representation of deletions

Returns:

  • (NillClass, String)


77
78
79
80
81
# File 'lib/hash_deep_diff/delta.rb', line 77

def addition
  return nil if right == NO_VALUE

  Report.new(path: path, value: right)
end

#complex?Bool

Returns true if we have nested Hashes

Returns:

  • (Bool)


23
24
25
# File 'lib/hash_deep_diff/delta.rb', line 23

def complex?
  left.respond_to?(:to_hash) && right.respond_to?(:to_hash)
end

#deletionNillClass, String (private)

Visual representation of additions

Returns:

  • (NillClass, String)


69
70
71
72
73
# File 'lib/hash_deep_diff/delta.rb', line 69

def deletion
  return nil if left == NO_VALUE

  Report.new(path: path, value: left, mode: Report::Mode::DELETION)
end

#leftObject

Original value



34
35
36
# File 'lib/hash_deep_diff/delta.rb', line 34

def left
  @value[:left]
end

#pathArray

Keys needed to fetch values that we’re comparing

Returns:

  • (Array)


29
30
31
# File 'lib/hash_deep_diff/delta.rb', line 29

def path
  @prefix + [@delta.keys.first]
end

#rightObject

Value we compare to



39
40
41
# File 'lib/hash_deep_diff/delta.rb', line 39

def right
  @value[:right]
end

#to_sObject

See #to_str



44
45
46
# File 'lib/hash_deep_diff/delta.rb', line 44

def to_s
  to_str
end

#to_strString

Visual representation of additions and deletiond at given path

Returns:

  • (String)


17
18
19
# File 'lib/hash_deep_diff/delta.rb', line 17

def to_str
  [deletion, addition].compact.join("\n")
end