Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Bugfix - Remove partial ANSI colour codes when truncating object.inspect #294

Merged
merged 1 commit into from
Aug 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions lib/rspec/support/object_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ def format(object)
if formatted_object.length < max_formatted_output_length
return formatted_object
else
beginning = formatted_object[0 .. max_formatted_output_length / 2]
ending = formatted_object[-max_formatted_output_length / 2 ..-1]
beginning = truncate_string formatted_object, 0, max_formatted_output_length / 2
ending = truncate_string formatted_object, -max_formatted_output_length / 2, -1
return beginning + ELLIPSIS + ending
end
end
Expand Down Expand Up @@ -244,6 +244,20 @@ def inspect
DelegatorInspector,
InspectableObjectInspector
]

private

# Returns the substring defined by the start_index and end_index
# If the string ends with a partial ANSI code code then that
# will be removed as printing partial ANSI
# codes to the terminal can lead to corruption
def truncate_string(str, start_index, end_index)
cut_str = str[start_index..end_index]

# ANSI color codes are like: \e[33m so anything with \e[ and a
# number without a 'm' is an incomplete color code
cut_str.sub(/\e\[\d+$/, '')
end
end
end
end
12 changes: 12 additions & 0 deletions spec/rspec/support/object_formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,18 @@ def self.to_s
formatter = ObjectFormatter.new(10)
expect(formatter.format('Testing')).to eq('"Testing"')
end

context 'with ANSI escape codes that fall on the truncate split' do
it 'removes that escape code so terminals do not get corrupted print a partial escape code' do
formatter = ObjectFormatter.new(38)
object = Class.new do
def inspect
"#<\e[33mClass\e[0m \e[36mname: \e[0m\"foobars\" \e[36mcount: \e[0m42>"
end
end.new
expect(formatter.format(object)).to eq("#<\e[33mClass\e[0m ...\e[36mcount: \e[0m42>")
end
end
end

context 'with truncation disabled' do
Expand Down