Class: Rbcat::Colorizer

Inherits:
Object
  • Object
show all
Defined in:
lib/rbcat/colorizer.rb

Class Method Summary collapse

Class Method Details

.colorize(string, predefined: nil, rules: nil, order: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbcat/colorizer.rb', line 9

def self.colorize(string, predefined: nil, rules: nil, order: nil)
  return string if ENV["RBCAT_COLORIZER"] == "false"

  colors = Rbcat::Colors::DEFAULT
  config = create_config(predefined, rules, order)

  config.each_value do |settings|
    if settings[:once]
      string.sub!(settings[:regexp]) do |match|
        colors[settings[:color]] + match + colors[:default]
      end
    elsif settings[:colors]
      string.gsub!(settings[:regexp]) do
        str = ""
        Regexp.last_match.captures.each_with_index do |match, i|
          str << colors[settings[:colors][i]] + match + colors[:default]
        end

        str
      end
    else
      string.gsub!(settings[:regexp]) do |match|
        colors[settings[:color]] + match + colors[:default]
      end
    end
  end

  string
end


3
4
5
6
7
# File 'lib/rbcat/colorizer.rb', line 3

def self.print_colors
  Rbcat::Colors::DEFAULT.each do |key, value|
    puts "#{value}#{key}\e[0m"
  end
end

.uncolorize(string) ⇒ Object



39
40
41
42
# File 'lib/rbcat/colorizer.rb', line 39

def self.uncolorize(string)
  pattern = /\033\[([0-9]+);([0-9]+)m|\033\[([0-9]+)m/m
  string.gsub(pattern, "")
end