Class: String

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

Constant Summary collapse

HIGHLIGHT =
{
  :end => "",
  :gray => "",
  :red => "",
  :green => "",
  :yellow => "",
  :blue => "",
  :purple => "",
  :lightblue => "",
  :white => "",
  :red_bg => "",
  :green_bg => "",
  :yellow_bg => "",
  :blue_bg => "",
  :purple_bg => "",
  :lightblue_bg => "",
  :white_bg => "",
  :bold => "",
  :default => ""
}

Instance Method Summary collapse

Instance Method Details

#hl(type = :bold, word = nil) ⇒ Object

Allow string highlighting with Unix terminal codes. The type of highlighting might be :bold, a color, e.g. :red, :blue or a background color, e.g. :red_bg, blue_bg, etc.

If the word is given, only the word will be highlighted. It is directly expanded in the Regexp, so you may use meta-characters, e.g. (John|Frank|Bill). It is also surrounded by anchors, so only whole words will be highlighted, e.g. “abc abcd”.hl(:bold,“abc”)

> abc abcd



35
36
37
38
39
40
41
42
# File 'lib/colors/string.rb', line 35

def hl(type=:bold,word=nil)
  if word
    self.gsub(/(\s|\A|[^[:alnum:]])#{word}(\s|\Z|[^[:alnum:]])/,
      "\\1" + HIGHLIGHT[type] + word.to_s + HIGHLIGHT[:end] + "\\2")
  else
    HIGHLIGHT[type] + self.to_s + HIGHLIGHT[:end]
  end
end