Github: https://github.com/myobie/htmldiff
# Gemfile
gem 'htmldiff', github: 'myobie/htmldiff', ref: 'c3b9112b34e9c37e805068ae3a6a42388666e67e'
Run bundle install
.
# app/services/string_diff.rb
class StringDiff
extend HTMLDiff
end
Lets add some methods to our class StringDiff
to generate pretty HTML diff between 2 strings.
# app/services/string_diff.rb
class StringDiff
def self.striked_html(original, modified)
self.diff(original, modified)
end
end
original = "a word now is here"
modified = "a second word is there"
StringDiff.striked_html(original, modified)
=> "a<ins class=\"diffins\"> second</ins> word <del class=\"diffdel\">now </del>is <del class=\"diffmod\">here</del><ins class=\"diffmod\">there</ins>"
# app/services/string_diff.rb
class StringDiff
def self.classified_html(original, modified)
striked_html(original, modified).gsub(/\<ins(.*?)\>/, "<span class='inserted'>").
gsub(/\<del(.*?)\>/, "<span class='deleted'>").
gsub(/\<\/(ins|del)\>/, '</span>')
end
end
StringDiff.classified_html(original, modified)
=> "a<span class='inserted'> second</span> word <span class='deleted'>now </span>is <span class='deleted'>here</span><span class='inserted'>there</span>"