summaryrefslogtreecommitdiff
path: root/lib/html_word_diff.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/html_word_diff.rb')
-rw-r--r--lib/html_word_diff.rb52
1 files changed, 52 insertions, 0 deletions
diff --git a/lib/html_word_diff.rb b/lib/html_word_diff.rb
new file mode 100644
index 0000000..1f28cf5
--- /dev/null
+++ b/lib/html_word_diff.rb
@@ -0,0 +1,52 @@
1require 'diff/lcs'
2
3module HtmlWordDiff
4 TOKEN_REGEXP = /<[^>]*>|[[:space:]]+|[[:alnum:]]+|[^[:space:][:alnum:]<>]/
5
6 def self.inline(old_html, new_html)
7 html = +''
8 each_change(old_html, new_html) do |action, old_token, new_token|
9 case action
10 when '='
11 html << new_token
12 when '-'
13 html << "<del>#{old_token}</del>"
14 when '+'
15 html << "<ins>#{new_token}</ins>"
16 when '!'
17 html << "<del>#{old_token}</del><ins>#{new_token}</ins>"
18 end
19 end
20 html
21 end
22
23 def self.side_by_side(old_html, new_html)
24 old_out = +''
25 new_out = +''
26 each_change(old_html, new_html) do |action, old_token, new_token|
27 case action
28 when '='
29 old_out << old_token
30 new_out << new_token
31 when '-'
32 old_out << "<del>#{old_token}</del>"
33 when '+'
34 new_out << "<ins>#{new_token}</ins>"
35 when '!'
36 old_out << "<del>#{old_token}</del>"
37 new_out << "<ins>#{new_token}</ins>"
38 end
39 end
40 [old_out, new_out]
41 end
42
43 def self.each_change(old_html, new_html)
44 Diff::LCS.sdiff(tokenize(old_html), tokenize(new_html)).each do |change|
45 yield change.action, change.old_element, change.new_element
46 end
47 end
48
49 def self.tokenize(html)
50 html.to_s.scan(TOKEN_REGEXP)
51 end
52end