Newy
Newy

Reputation: 40147

Showing a diff between two bodies of text in Rails

Is there an easy way to do this - create marked up text that shows the changes between two pieces of text. A built-in helper maybe? Looked but couldn't find!

Upvotes: 15

Views: 4834

Answers (4)

Dzmitry
Dzmitry

Reputation: 466

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

Upvotes: 1

Shakeeb Ahmad
Shakeeb Ahmad

Reputation: 2030

For anyone looking for an answer today: https://github.com/samg/diffy is the safest bet. As the other gems and libraries mentioned here have been abandoned since some time now.

Upvotes: 6

Robbie
Robbie

Reputation: 725

http://github.com/pvande/differ You could use that, which performs diff's on strings. You'd have to build some logic to format it into an output ready state. Probably using Builder::XmlMarkup in a helper.

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

Which seems to output markup - but it's not very well documented.

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

Upvotes: 6

jonnii
jonnii

Reputation: 28322

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

Upvotes: 5

Related Questions