class Unparser::Diff
Class to create diffs from source code
Constants
- ADDITION
- DELETION
- NEWLINE
Public Class Methods
build(old, new)
click to toggle source
Build new object from source strings
@param [String] old @param [String] new
@return [Diff]
# File lib/unparser/diff.rb, line 46 def self.build(old, new) new(lines(old), lines(new)) end
Private Class Methods
colorize_line(line)
click to toggle source
# File lib/unparser/diff.rb, line 85 def self.colorize_line(line) case line[0] when ADDITION Color::GREEN when DELETION Color::RED else Color::NONE end.format(line) end
lines(source)
click to toggle source
Break up source into lines
@param [String] source
@return [Array<String>]
# File lib/unparser/diff.rb, line 55 def self.lines(source) source.lines.map(&:chomp) end
Public Instance Methods
colorized_diff()
click to toggle source
Colorized unified source diff between old and new
@return [String]
if there is a diff
@return [nil]
otherwise
# File lib/unparser/diff.rb, line 33 def colorized_diff return unless diff diff.lines.map(&self.class.method(:colorize_line)).join end
diff()
click to toggle source
Unified source diff between old and new
@return [String]
if there is exactly one diff
@return [nil]
otherwise
# File lib/unparser/diff.rb, line 19 def diff return if diffs.empty? minimized_hunk.diff(:unified) + NEWLINE end
Private Instance Methods
diffs()
click to toggle source
# File lib/unparser/diff.rb, line 62 def diffs ::Diff::LCS.diff(old, new) end
hunks()
click to toggle source
# File lib/unparser/diff.rb, line 66 def hunks diffs.map do |diff| ::Diff::LCS::Hunk.new(old.map(&:dup), new, diff, max_length, 0) end end
max_length()
click to toggle source
# File lib/unparser/diff.rb, line 81 def max_length [old, new].map(&:length).max end
minimized_hunk()
click to toggle source
# File lib/unparser/diff.rb, line 72 def minimized_hunk head, *tail = hunks tail.reduce(head) do |left, right| right.merge(left) right end end