Display the difference between two text bodies in Rails

Is there an easy way to do this - create tagged text that shows the changes between two pieces of text. Maybe a built-in helper? Looked, but could not find!

+13
ruby-on-rails
May 12, '10 at 21:35
source share
4 answers

You can do this completely on the client side in javascript using something like jsdifflib ( http://snowtide.com/jsdifflib ).

+6
May 12 '10 at 21:38
source share

http://github.com/pvande/differ You can use this, which performs diff for strings. You will need to build some logic to format it in a state of readiness for release. Perhaps using Builder :: XmlMarkup in the helper.

There also: http://github.com/myobie/htmldiff

The markup output seems to be - but it is not very well documented.

As for the built-in helper, I don't think that Rails has anything built-in. There http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Hash/Diff.html - but unlike the first plugin, this is used for hashes, not for strings.

+5
May 12, '10 at 21:46
source share

For those seeking an answer today: https://github.com/samg/diffy is the safest bet. Because the other gems and libraries mentioned here have been discarded since some time.

+2
Apr 25 '15 at 18:51
source share

There are two ways:

1.works also for non-English string

class String def -(other) s1 = self.mb_chars.downcase.chars s2 = other.mb_chars.downcase.chars s1.size >= s2.size ? s1 - s2 : s2 - s1 end end > 'abcde' - 'abc' => ["d", "e"] > 'abc' - 'ac' => ["b"] 

2.from http://tobyho.com/2011/03/26/string-difference-in-ruby/

 class String def -(other) self.index(other) == 0 ? self[other.size..self.size] : nil end end > 'abcde' - 'abc' => "de" but > 'abc' - 'ac' => nil 
0
Mar 03 '17 at 7:42 on
source share



All Articles