Class: Markdiff::Operations::TextDiffOperation

Inherits:
Base
  • Object
show all
Defined in:
lib/markdiff/operations/text_diff_operation.rb

Instance Attribute Summary

Attributes inherited from Base

#target_node

Instance Method Summary collapse

Constructor Details

#initialize(after_node:, **args) ⇒ TextDiffOperation

Returns a new instance of TextDiffOperation.

Parameters:

  • after_node (Nokogiri::XML::Node)


9
10
11
12
# File 'lib/markdiff/operations/text_diff_operation.rb', line 9

def initialize(after_node:, **args)
  super(**args)
  @after_node = after_node
end

Instance Method Details

#inserted_nodeNokogiri::XML::Node

Returns:

  • (Nokogiri::XML::Node)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/markdiff/operations/text_diff_operation.rb', line 15

def inserted_node
  before_elements = target_node.to_s.split(' ')
  after_elements = @after_node.to_s.split(' ')
  last_operation = nil

  groupings = ::Diff::LCS.sdiff(before_elements, after_elements)
    .slice_when { |prev, cur| prev.action != cur.action }

  output = groupings.map do |grouping|
    action = grouping.first.action

    response = case action
      when "="
        grouping.map(&:new_element).join(" ")
      when "-"
        %(<del class="del">#{grouping.map(&:old_element).join(" ")}</del>)
      when "+"
        %(<ins class="ins ins-before">#{grouping.map(&:new_element).join(" ")}</ins>)
      when "!"
        %(<del class="del">#{grouping.map(&:old_element).join(" ")}</del><ins class="ins ins-after">#{grouping.map(&:new_element).join(" ")}</ins>)
      else
        raise "Unknown action #{action}"
    end

    response = " #{response}" if last_operation && last_operation != '+'

    last_operation = action

    response
  end

  ::Nokogiri::HTML.fragment(output.join(''))
end

#priorityObject



49
50
51
# File 'lib/markdiff/operations/text_diff_operation.rb', line 49

def priority
  1
end