Class: RSpec::Support::Differ

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/support/differ.rb

Overview

rubocop:disable Metrics/ClassLength

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Differ

Returns a new instance of Differ.



69
70
71
72
# File 'lib/rspec/support/differ.rb', line 69

def initialize(opts={})
  @color = opts.fetch(:color, false)
  @object_preparer = opts.fetch(:object_preparer, lambda { |string| string })
end

Instance Method Details

#color?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/rspec/support/differ.rb', line 65

def color?
  @color
end

#diff(actual, expected) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rspec/support/differ.rb', line 13

def diff(actual, expected)
  diff = ""

  unless actual.nil? || expected.nil?
    if all_strings?(actual, expected)
      if any_multiline_strings?(actual, expected)
        diff = diff_as_string(coerce_to_string(actual), coerce_to_string(expected))
      end
    elsif no_procs?(actual, expected) && no_numbers?(actual, expected)
      diff = diff_as_object(actual, expected)
    end
  end

  diff.to_s
end

#diff_as_object(actual, expected) ⇒ Object

rubocop:enable Metrics/MethodLength



59
60
61
62
63
# File 'lib/rspec/support/differ.rb', line 59

def diff_as_object(actual, expected)
  actual_as_string = object_to_string(actual)
  expected_as_string = object_to_string(expected)
  diff_as_string(actual_as_string, expected_as_string)
end

#diff_as_string(actual, expected) ⇒ Object

rubocop:disable Metrics/MethodLength



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
56
# File 'lib/rspec/support/differ.rb', line 30

def diff_as_string(actual, expected)
  encoding = EncodedString.pick_encoding(actual, expected)

  actual   = EncodedString.new(actual, encoding)
  expected = EncodedString.new(expected, encoding)

  output = EncodedString.new("\n", encoding)
  hunks = build_hunks(actual, expected)

  hunks.each_cons(2) do |prev_hunk, current_hunk|
    begin
      if current_hunk.overlaps?(prev_hunk)
        add_old_hunk_to_hunk(current_hunk, prev_hunk)
      else
        add_to_output(output, prev_hunk.diff(format_type).to_s)
      end
    ensure
      add_to_output(output, "\n")
    end
  end

  finalize_output(output, hunks.last.diff(format_type).to_s) if hunks.last

  color_diff output
rescue Encoding::CompatibilityError
  handle_encoding_errors(actual, expected)
end