Class: MiniSpec::Differ

Inherits:
Object
  • Object
show all
Defined in:
lib/minispec/utils/differ.rb

Defined Under Namespace

Classes: EncodedString, HunkGenerator

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Differ

Returns a new instance of Differ.



184
185
186
187
# File 'lib/minispec/utils/differ.rb', line 184

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.



182
183
184
# File 'lib/minispec/utils/differ.rb', line 182

def color
  @color
end

#diff(actual, expected) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/minispec/utils/differ.rb', line 130

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



175
176
177
178
179
# File 'lib/minispec/utils/differ.rb', line 175

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



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/minispec/utils/differ.rb', line 146

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).to_s)
      end
    ensure
      add_to_output(output, "\n")
    end
  end

  if hunks.last
    finalize_output(output, hunks.last.diff(format).to_s)
  end

  color_diff output
rescue Encoding::CompatibilityError
  handle_encoding_errors
end