Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/colorit/string.rb

Overview

monkey-patch String to color strings and patterns in strings

Instance Method Summary collapse

Instance Method Details

#colorize(pattern, color) ⇒ Object

colorize an arbitrary string



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/colorit/string.rb', line 7

def colorize(pattern, color)
  begin
    gsub(pattern) do
      Colorit::Colors.all[color] + $& + Colorit::Colors.reset()
    end
  rescue ArgumentError
    require 'iconv'

    # rescue from invalid byte sequence in UTF-8 and convert it to UTF-8
    # and ignore these sequences to get a safe string
    ic = Iconv.new("UTF-8//IGNORE", "UTF-8")
    ic.iconv(self).colorize(pattern, color)
  end
end