Class: RubyJard::Decorators::ColorDecorator

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_jard/decorators/color_decorator.rb

Overview

Manipulate and decorate color for texts. This class translate colors to corresponding escape sequences. Support 24-bit color (#51617d format) or 256 colors (https://jonasjacek.github.io/colors/) Example:

  • #fafafa => \e[38;2;250;250;250m
  • #aaa => \e[38;2;170;170;170m
  • 77 => \e[38;2;170;170;170m

Constant Summary collapse

HEX_PATTERN_6 =
/^#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})$/i.freeze
HEX_PATTERN_3 =
/^#([A-Fa-f0-9]{1})([A-Fa-f0-9]{1})([A-Fa-f0-9]{1})$/i.freeze
XTERM_NUMBER_PATTERN =
/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/i.freeze
CSI_RESET =
"\e[0m"
CSI_FOREGROUND_24BIT =
"\e[38;2;%d;%d;%dm"
CSI_BACKGROUND_24BIT =
"\e[48;2;%d;%d;%dm"
CSI_FOREGROUND_256 =
"\e[38;5;%dm"
CSI_BACKGROUND_256 =
"\e[48;5;%dm"
CSI_ITALIC =
"\e[3m"
CSI_UNDERLINE =
"\e[4m"
CSI_BOLD =
"\e[1m"
STYLES_CSI_MAP =
{
  underline: CSI_UNDERLINE,
  italic: CSI_ITALIC,
  bold: CSI_BOLD
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(color_scheme) ⇒ ColorDecorator

Returns a new instance of ColorDecorator.



34
35
36
# File 'lib/ruby_jard/decorators/color_decorator.rb', line 34

def initialize(color_scheme)
  @color_scheme = color_scheme
end

Instance Method Details

#decorate(style_names, content) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ruby_jard/decorators/color_decorator.rb', line 38

def decorate(style_names, content)
  attributes = nil
  foreground = nil
  background = nil

  if style_names.is_a?(Symbol)
    styles = @color_scheme.styles_for(style_names)
  else
    attributes = translate_styles(style_names)
    styles = @color_scheme.styles_for(style_names.shift)
  end

  if styles.is_a?(Array)
    foreground = translate_color(styles.shift, true)
    background = translate_color(styles.shift, false)
  elsif !styles.nil?
    raise RubyJard::Error, "Styles for #{style_names.inspect} must be an array"
  end

  "#{foreground}#{background}#{attributes}#{content}#{CSI_RESET}"
end