Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Created December 15, 2017 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagdeepsingh/42474326918515d885fe967672d0ef06 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/42474326918515d885fe967672d0ef06 to your computer and use it in GitHub Desktop.
htmldiff - Inline diff for strings using html tags

htmldiff

Github: https://github.com/myobie/htmldiff

1 Install gem

# Gemfile
gem 'htmldiff', github: 'myobie/htmldiff', ref: 'c3b9112b34e9c37e805068ae3a6a42388666e67e'

Run bundle install.

2 Extend module HTMLDiff

# app/services/string_diff.rb
class StringDiff
  extend HTMLDiff
end

3 Generate diff

Lets add some methods to our class StringDiff to generate pretty HTML diff between 2 strings.

3.1 striked_html

# 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>"

3.2 classified_html

# 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>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment