Class: Raif::PromptDiff
- Inherits:
-
Object
- Object
- Raif::PromptDiff
- Defined in:
- lib/raif/prompt_diff.rb
Overview
Line-level diff of two prompts, with word-level highlighting inside changed line pairs. Returns plain data so views can render (and escape) the text themselves.
Defined Under Namespace
Constant Summary collapse
- WORD_DIFF_TOKEN_LIMIT =
Lines with more tokens than this skip the word diff and are highlighted as a whole.
2_000- WORD_DIFF_MIN_SIMILARITY =
Line pairs that share less than this fraction of their words are highlighted as a whole.
0.5
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(original, current) ⇒ PromptDiff
constructor
A new instance of PromptDiff.
- #lines ⇒ Object
Constructor Details
#initialize(original, current) ⇒ PromptDiff
Returns a new instance of PromptDiff.
20 21 22 23 |
# File 'lib/raif/prompt_diff.rb', line 20 def initialize(original, current) @original_lines = original.to_s.strip.lines(chomp: true) @current_lines = current.to_s.strip.lines(chomp: true) end |
Class Method Details
.build(original, current) ⇒ Object
16 17 18 |
# File 'lib/raif/prompt_diff.rb', line 16 def self.build(original, current) new(original, current).lines end |
Instance Method Details
#lines ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/raif/prompt_diff.rb', line 25 def lines result = [] deleted = [] added = [] Diff::LCS.sdiff(@original_lines, @current_lines).each do |change| case change.action when "=" result.concat(deleted).concat(added) deleted = [] added = [] result << Line.new(:unchanged, [Segment.new(change.old_element, false)]) when "-" deleted << Line.new(:deleted, [Segment.new(change.old_element, true)]) when "+" added << Line.new(:added, [Segment.new(change.new_element, true)]) when "!" old_segments, new_segments = word_diff(change.old_element, change.new_element) deleted << Line.new(:deleted, old_segments) added << Line.new(:added, new_segments) end end result.concat(deleted).concat(added) end |