Class: DiffTools::SimpleDiff
- Inherits:
-
Object
- Object
- DiffTools::SimpleDiff
- Defined in:
- app/lib/diff_tools.rb
Instance Method Summary collapse
-
#initialize(old_value, new_value) ⇒ SimpleDiff
constructor
A new instance of SimpleDiff.
- #to_html ⇒ Object
Constructor Details
#initialize(old_value, new_value) ⇒ SimpleDiff
Returns a new instance of SimpleDiff.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'app/lib/diff_tools.rb', line 7 def initialize(old_value, new_value) # /\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:, old: changes.map(&:old_element).join, new: changes.map(&:new_element).join } end end |
Instance Method Details
#to_html ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'app/lib/diff_tools.rb', line 24 def to_html @changes.map do |chunk| old_html = DiffTools.value_to_html(chunk[:old]) new_html = DiffTools.value_to_html(chunk[:new]) if chunk[:action] == "=" new_html else (old_html.empty? ? "" : "<del>#{old_html}</del>") + \ (new_html.empty? ? "" : "<ins>#{new_html}</ins>") end end.join end |