Class: DiffString

Inherits:
Object
  • Object
show all
Includes:
Colors
Defined in:
lib/diff_string.rb

Overview

An added or removed part of a diff, which can contain both highlighted and not highlighted characters. For multi line strings, each line will be prefixed with prefix and color.

Constant Summary

Constants included from Colors

Colors::BOLD, Colors::CYAN, Colors::ESC, Colors::GREEN, Colors::NOT_REVERSE, Colors::RED, Colors::RESET, Colors::REVERSE

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Colors

#reversed, #uncolor

Constructor Details

#initialize(prefix, color) ⇒ DiffString

Returns a new instance of DiffString.



10
11
12
13
14
15
# File 'lib/diff_string.rb', line 10

def initialize(prefix, color)
  @reverse = false
  @prefix = prefix
  @color = color
  @string = ''
end

Class Method Details

.decorate_string(prefix, color, string) ⇒ Object



47
48
49
50
51
# File 'lib/diff_string.rb', line 47

def self.decorate_string(prefix, color, string)
  decorated = DiffString.new(prefix, color)
  decorated.add(string, false)
  return decorated.to_s
end

Instance Method Details

#add(string, reverse) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/diff_string.rb', line 17

def add(string, reverse)
  if reverse && string == "\n"
    add('↵', true)
    add("\n", false)
    return
  end

  if @string.empty?() || @string.end_with?("\n")
    @string += @color
    @string += @prefix
  end

  if reverse != @reverse
    @string += reverse ? REVERSE : NOT_REVERSE
  end
  @reverse = reverse

  @string += string
end

#to_sObject



37
38
39
40
41
42
43
44
45
# File 'lib/diff_string.rb', line 37

def to_s()
  return '' if @string.empty?

  string = @string
  string.chomp! if string.end_with? "\n"

  suffix = @color.empty? ? '' : RESET
  return string + suffix + "\n"
end