Method: Kronk::Diff#create_diff

Defined in:
lib/kronk/diff.rb

#create_diffObject

Returns a diff array with the following format:

str1 = "match1\nmatch2\nstr1 val"
str1 = "match1\nin str2\nmore str2\nmatch2\nstr2 val"

Diff.new(str1, str2).create_diff
#=> ["match 1",
#   [[], ["in str2", "more str2"]],
#   "match 2",
#   [["str1 val"], ["str2 val"]]]


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/kronk/diff.rb', line 63

def create_diff
  diff_ary = []
  return @str1.split @char if @str1 == @str2

  arr1 = @str1.split @char
  arr2 = @str2.split @char

  common_list = find_common arr1, arr2

  return [[arr1, arr2]] if common_list.empty?

  last_i1 = 0
  last_i2 = 0

  common_list.each do |c|
    next unless c

    left  = arr1[last_i1...c[1]]
    right = arr2[last_i2...c[2]]

    # add diffs
    unless left.empty? && right.empty?
      @meta << []
      @meta.last[0] = left[0].meta[0]  if left[0].respond_to?(:meta)
      @meta.last[1] = right[0].meta[0] if right[0].respond_to?(:meta)

      diff_ary << [left, right]
    end

    # add common
    arr1[c[1], c[0]].each_with_index do |str1, i|
      str2 = arr2[c[2]+i]
      @meta << []
      @meta.last[0] = str1.meta[0] if str1.respond_to?(:meta)
      @meta.last[1] = str2.meta[0] if str2.respond_to?(:meta)
    end

    diff_ary.concat arr1[c[1], c[0]]

    last_i1 = c[1] + c[0]
    last_i2 = c[2] + c[0]
  end

  left  = arr1[last_i1..-1]
  right = arr2[last_i2..-1]

  diff_ary << [left, right] unless left.empty? && right.empty?

  diff_ary
end