Class: Wrong::ArrayDiff

Inherits:
FailureMessage::Formatter show all
Defined in:
lib/wrong/message/array_diff.rb

Instance Attribute Summary

Attributes inherited from FailureMessage::Formatter

#predicate

Instance Method Summary collapse

Methods inherited from FailureMessage::Formatter

#initialize, register

Constructor Details

This class inherits a constructor from Wrong::FailureMessage::Formatter

Instance Method Details

#arrayish?(object) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
17
# File 'lib/wrong/message/array_diff.rb', line 14

def arrayish?(object)
  # in some Rubies, String is Enumerable
  object.is_a?(Enumerable) && !(object.is_a?(String) || object.is_a?(Hash))
end

#compute_and_format(left, right) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/wrong/message/array_diff.rb', line 30

def compute_and_format(left, right)
  diffs = Diff::LCS.sdiff(left, right)

  left_arr = []
  right_arr = []
  diff_arr = []

  diffs.each do |diff|
    left_elem = diff.old_element.nil? ? "nil" : diff.old_element.inspect
    right_elem = diff.new_element.nil? ? "nil" : diff.new_element.inspect

    max_length = [left_elem.length, right_elem.length].max
    left_arr << left_elem.ljust(max_length) unless diff.action == "+"
    right_arr << right_elem.ljust(max_length) unless diff.action == "-"
    diff_arr << (diff.action == "=" ? " ".ljust(max_length) : "^".ljust(max_length))
  end


  diff_str = " " + diff_arr.join("  ") + " "

  [format(left_arr), format(right_arr), diff_str]
end

#describeObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/wrong/message/array_diff.rb', line 19

def describe
  left_str, right_str, diff_str = compute_and_format(predicate.left, predicate.right)

  message = "\n"
  message << left_str + "\n"
  message << right_str + "\n"
  message << diff_str + "\n"
  message

end

#format(thing) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/wrong/message/array_diff.rb', line 53

def format(thing)
  str = ""
  if thing.is_a?(Array)
    str << "["
    thing.each_with_index do |item, i|
      str << format(item)
      str << ", " unless i == thing.length-1
    end
    str << "]"
  else
    str << thing
  end
  str
end

#match?Boolean

Returns:

  • (Boolean)


8
9
10
11
12
# File 'lib/wrong/message/array_diff.rb', line 8

def match?
  predicate.is_a?(Predicated::Equal) &&
          arrayish?(predicate.left) &&
          arrayish?(predicate.right)
end