Class: RSpec::Support::Differ

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

Overview

rubocop:disable ClassLength

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Differ

Returns a new instance of Differ.



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

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

Instance Method Details

#color?Object

Returns the value of attribute color.



62
63
64
# File 'lib/rspec/support/differ.rb', line 62

def color
  @color
end

#diff(actual, expected) ⇒ Object



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

def diff(actual, expected)
  diff = ""

  if actual && expected
    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 MethodLength



55
56
57
58
59
# File 'lib/rspec/support/differ.rb', line 55

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 MethodLength



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rspec/support/differ.rb', line 27

def diff_as_string(actual, expected)
  @encoding = pick_encoding actual, expected

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

  output = EncodedString.new("\n", @encoding)

  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
end