Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

For readablity, diff on a word-by-word rather than character-by-character basis #799

Merged
merged 9 commits into from
Dec 23, 2022
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
9 changes: 7 additions & 2 deletions app/lib/diff_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
module DiffTools
class SimpleDiff
def initialize(old_value, new_value)
old_value = old_value.to_s
new_value = new_value.to_s
# /\b/ matches word boundaries.
# It is a zero-length match before and after each word,
# and it preserves the whitespace between words.
#
# "cat dog".split /\b/ == ["cat", " ", "dog"]
old_value = old_value.to_s.split(/\b/)
new_value = new_value.to_s.split(/\b/)
@changes = ::Diff::LCS.sdiff(old_value, new_value).chunk(&:action).map do |action, changes|
{
action: action,
Expand Down
8 changes: 4 additions & 4 deletions spec/lib/diff_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
expect(DiffTools::SimpleDiff.new("cat", "dog").to_html).to eq "<del>cat</del><ins>dog</ins>"
end
it "handles single character change" do
expect(DiffTools::SimpleDiff.new("cat", "bat").to_html).to eq "<del>c</del><ins>b</ins>at"
expect(DiffTools::SimpleDiff.new("cat", "bat").to_html).to eq "<del>cat</del><ins>bat</ins>"
end

it "handles nil old" do
Expand All @@ -34,17 +34,17 @@
expect(DiffTools::SimpleDiff.new("2022", 2022).to_html).to eq "2022"
end
it "handles numbers" do
expect(DiffTools::SimpleDiff.new(2022, 2023).to_html).to eq "202<del>2</del><ins>3</ins>"
expect(DiffTools::SimpleDiff.new(2022, 2023).to_html).to eq "<del>2022</del><ins>2023</ins>"
end

it "encodes html" do
expect(DiffTools::SimpleDiff.new("1 < 2", "2 > 1").to_html).to eq "<del>1</del><ins>2</ins> <del>&lt;</del><ins>&gt;</ins> <del>2</del><ins>1</ins>"
expect(DiffTools::SimpleDiff.new("1 < 2", "2 > 1").to_html).to eq "<del>1 &lt; </del>2<ins> &gt; 1</ins>"
end

it "abbreviates really long strings" do
expect(DiffTools::SimpleDiff.new(
"This does not repeat the entire string if its just a tiny typo in the middle that changes.",
"This does not repeat the entire string if it's just a tiny typo in the middle that changes."
).to_html).to eq "This does not ... string if it<ins>&#39;</ins>s just a ... middle that changes."
).to_html).to eq "This does not ... entire string if <del>its</del><ins>it</ins><ins>&#39;s</ins> just a tiny ... middle that changes."
end
end