Class: ColorString

Inherits:
Delegator
  • Object
show all
Defined in:
lib/mmtop/string_colorize.rb

Constant Summary collapse

OFF =
"\e[0m"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, color) ⇒ ColorString

Returns a new instance of ColorString.



5
6
7
8
9
10
11
12
13
# File 'lib/mmtop/string_colorize.rb', line 5

def initialize(string, color)
  @string = string

  if color.is_a?(Array)
    @color_offsets = color
  else
    @color_offsets = [ [0, string.size, color] ]
  end
end

Instance Attribute Details

#color_offsetsObject (readonly)

Returns the value of attribute color_offsets.



15
16
17
# File 'lib/mmtop/string_colorize.rb', line 15

def color_offsets
  @color_offsets
end

Instance Method Details

#+(other) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mmtop/string_colorize.rb', line 27

def +(other)
  res = @string + other
  if other.is_a?(ColorString)
    adjusted_offsets = other.color_offsets.map do |arr|
      [arr[0] + @string.size, arr[1], arr[2]]
    end
    ColorString.new(res, @color_offsets + adjusted_offsets)
  else
    ColorString.new(res, @color_offsets + [[@string.size, other.size, OFF]])
  end 
end

#__getobj__Object



17
18
19
# File 'lib/mmtop/string_colorize.rb', line 17

def __getobj__
  @string
end

#to_sObject



21
22
23
24
25
# File 'lib/mmtop/string_colorize.rb', line 21

def to_s
  @color_offsets.map { |o|
    o.last + @string[o[0], o[1]] + OFF
  }.join
end