Class: Prettys::Colorizer

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

Instance Method Summary collapse

Instance Method Details

#colorize(options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/colorizer.rb', line 41

def colorize(options = {})
  options = add_default_options(options)
  unless [:background, :foreground].include?(options[:type])
    raise(ArgumentError, "Type must be a :background or :foreground")
  end
  marked_strings = Matcher.marked_strings(options[:string], options[:pattern])
  marked_strings.map do |ms| 
    if ms[:marked]
      escaped_string({
        string: ms[:string],
        pattern: options[:pattern],
        type: options[:type],
        bold: options[:bold],
        color: options[:color]
      })
    else
      ms[:string]
    end
  end.join
end

#end_of_escape_sequenceObject



33
34
35
# File 'lib/colorizer.rb', line 33

def end_of_escape_sequence
  "\e[0m"
end

#escape_sequence(options) ⇒ Object



26
27
28
29
30
31
# File 'lib/colorizer.rb', line 26

def escape_sequence(options)
  options = add_default_options(options)
  color_code = COLORS[options[:color]]
  color_code += 10 if options[:type] == :background
  "\e[#{color_code.to_s};#{(options[:bold] ? 1 : 2).to_s}m"
end

#escaped_string(options) ⇒ Object



37
38
39
# File 'lib/colorizer.rb', line 37

def escaped_string(options)
  escape_sequence(options) + options[:string] + end_of_escape_sequence
end