使diff-lcs的输出成为可读的

我正在使用diff-lcs gem来输出两个html内容体之间的差异。 这是示例内容。

第一版:

Paragraph one. Sentence one.

Paragraph two. Another sentence.

Paragraph three. I dare you to change me!

第二版:

 

Paragraph one. Sentence two.

Paragraph two. Another sentence.

Paragraph three. I dare you to update me!

使用这个:

 seq1 = @versionOne.body seq2 = @versionTwo.body seq = Diff::LCS.diff(seq1, seq2) 

你得到这个怪物:

 seq => [[#, #], [#, #], [#, #, #, #, #], [#, #, #], [#]] 

文档中的sdiff和其他方法的输出同样令人恐惧。 我理解数组(数组)的结构,但必须有一种简单的方法来以人类可读和风格的方式显示差异。

PS – 如果有人想创建diff-lcs标签,那将不胜感激。

我正在为diff-lcs提供的是一个常规字符串 – 一个字符数组。 如果我想要的是人物的比较,我得到了我想要的东西,但我想要更具可读性的东西 – 比较单词,句子或句子。 我选择了句子。

 seq1 = @versionOne.body.split('.') seq2 = @versionTwo.body.split('.') compareDiff = Diff::LCS.sdiff(seq1, seq2) 

这产生了更具可读性和可解析性的内容。 实际上,我也想分开!? 。 然而,该结构不是正常的数组或散列数组。 浏览器中的输出让我失望,但它是一个对象数组,你可以像其他任何东西一样解析它。 这是我在rails控制台中获得的YAML格式化输出(不知道为什么它没有在浏览器中显示):

 --- - !ruby/object:Diff::LCS::ContextChange action: "=" new_element: 

Paragraph one new_position: 0 old_element:

Paragraph one old_position: 0 - !ruby/object:Diff::LCS::ContextChange action: "!" new_element: " Sentence two" new_position: 1 old_element: " Sentence one" old_position: 1 - !ruby/object:Diff::LCS::ContextChange action: "=" new_element: |-

Paragraph two new_position: 2 old_element: |-

Paragraph two old_position: 2 - !ruby/object:Diff::LCS::ContextChange action: "=" new_element: " Another sentence" new_position: 3 old_element: " Another sentence" old_position: 3 - !ruby/object:Diff::LCS::ContextChange action: "=" new_element: |-

Paragraph three new_position: 4 old_element: |-

Paragraph three old_position: 4 - !ruby/object:Diff::LCS::ContextChange action: "!" new_element: " I dare you to update me!

" new_position: 5 old_element: " I dare you to change me!" old_position: 5 => nil

超级有帮助! 这将输出类似wiki的差异:

 sdiff = Diff::LCS.sdiff(seq2, seq1) diffHTML = '' sdiff.each do |diff| case diff.action when '=' diffHTML << diff.new_element + "." when '!' # strip_tags only needed on old_element. removes pre-mature end tags. diffHTML << "#{diff.old_element.strip_tags} #{diff.new_element}. " end end @compareBody = diffHTML.html ...[format do block] 

然后根据需要设置样式 。 如果你正在寻找更容易的东西,可能就是它的困难 ,但是一旦你搞清楚它就会非常灵活。