Class: Pastel::Color

Inherits:
Object
  • Object
show all
Includes:
ANSI
Defined in:
lib/pastel/color.rb

Overview

A class responsible for coloring strings.

Constant Summary collapse

ALIASES =

All color aliases

{}
ANSI_COLOR_REGEXP =

Match all color escape sequences

/\x1b\[{1,2}[0-9;:?]*m/mo.freeze

Constants included from ANSI

ANSI::ATTRIBUTES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ANSI

background?, foreground?, style?

Constructor Details

#initialize(enabled: nil, eachline: false) ⇒ Color

Initialize a Terminal Color


24
25
26
27
28
# File 'lib/pastel/color.rb', line 24

def initialize(enabled: nil, eachline: false)
  @enabled  = enabled
  @eachline = eachline
  @cache    = {}
end

Instance Attribute Details

#eachlineObject (readonly)

Returns the value of attribute eachline


19
20
21
# File 'lib/pastel/color.rb', line 19

def eachline
  @eachline
end

#enabledObject (readonly) Also known as: enabled?

Returns the value of attribute enabled


16
17
18
# File 'lib/pastel/color.rb', line 16

def enabled
  @enabled
end

Instance Method Details

#==(other) ⇒ Boolean

Compare colors for equivalence of attributes

Returns:

  • (Boolean)

235
236
237
238
# File 'lib/pastel/color.rb', line 235

def ==(other)
  other.is_a?(self.class) &&
    enabled == other.enabled && eachline == other.eachline
end

#alias_color(alias_name, *colors) ⇒ Array[String]

Define a new colors alias

Parameters:

  • alias_name (String)

    the colors alias to define

  • color (Array[Symbol,String])

    the colors the alias will correspond to

Returns:

  • (Array[String])

    the standard color values of the alias


206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/pastel/color.rb', line 206

def alias_color(alias_name, *colors)
  validate(*colors)

  if !(alias_name.to_s =~ /^[\w]+$/)
    raise InvalidAliasNameError, "Invalid alias name `#{alias_name}`"
  elsif ANSI::ATTRIBUTES[alias_name]
    raise InvalidAliasNameError,
          "Cannot alias standard color `#{alias_name}`"
  end

  ALIASES[alias_name.to_sym] = colors.map(&ANSI::ATTRIBUTES.method(:[]))
  colors
end

#apply_codes(string, ansi_colors) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Apply escape codes to the string

Parameters:

  • string (String)

    the string to apply escapes to

  • ansi_colors (Strin)

    the ansi colors to apply

Returns:

  • (String)

    return the string surrounded by escape codes


78
79
80
# File 'lib/pastel/color.rb', line 78

def apply_codes(string, ansi_colors)
  "#{ansi_colors}#{string.gsub(/(\e\[0m)([^\e]+)$/, "\\1#{ansi_colors}\\2")}\e[0m"
end

#clearObject

Reset sequence


85
86
87
# File 'lib/pastel/color.rb', line 85

def clear
  lookup(:clear)
end

#code(*colors) ⇒ Array[String]

Return raw color code without embeding it into a string.

Returns:

  • (Array[String])

    ANSI escape codes


148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/pastel/color.rb', line 148

def code(*colors)
  attribute = []
  colors.each do |color|
    value = ANSI::ATTRIBUTES[color] || ALIASES[color]
    if value
      attribute << value
    else
      validate(color)
    end
  end
  attribute
end

#colored?(string) ⇒ Boolean

Check if string has color escape codes

Parameters:

  • string (String)

    the string to check for color strings

Returns:

  • (Boolean)

    true when string contains color codes, false otherwise


117
118
119
# File 'lib/pastel/color.rb', line 117

def colored?(string)
  !ANSI_COLOR_REGEXP.match(string).nil?
end

#decorate(string, *colors) ⇒ String

Apply ANSI color to the given string.

Wraps eachline with clear escape.

Examples:

color.decorate "text", :yellow, :on_green, :underline

Parameters:

  • string (String)

    text to add ANSI strings

  • colors (Array[Symbol])

    the color names

Returns:

  • (String)

    the colored string


54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pastel/color.rb', line 54

def decorate(string, *colors)
  return string if blank?(string) || !enabled || colors.empty?

  ansi_colors = lookup(*colors.dup.uniq)
  if eachline
    string.dup.split(eachline).map! do |line|
      apply_codes(line, ansi_colors)
    end.join(eachline)
  else
    apply_codes(string.dup, ansi_colors)
  end
end

#disable!Object

Disable coloring of this terminal session


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

def disable!
  @enabled = false
end

#eql?(other) ⇒ Boolean

Compare colors for equality of attributes

Returns:

  • (Boolean)

225
226
227
228
# File 'lib/pastel/color.rb', line 225

def eql?(other)
  instance_of?(other.class) &&
    enabled.eql?(other.enabled) && eachline.eql?(other.eachline)
end

#hashNumeric

Hash for this instance and its attributes

Returns:

  • (Numeric)

254
255
256
# File 'lib/pastel/color.rb', line 254

def hash
  [self.class, enabled, eachline].hash
end

#inspectString

Inspect this instance attributes

Returns:

  • (String)

245
246
247
# File 'lib/pastel/color.rb', line 245

def inspect
  "#<#{self.class.name} enabled=#{enabled.inspect} eachline=#{eachline.inspect}>"
end

#lookup(*colors) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Find the escape code for a given set of color attributes

Examples:

color.lookup(:red, :on_green) # => "\e[31;42m"

Parameters:

  • colors (Array[Symbol])

    the list of color name(s) to lookup

Returns:

  • (String)

    the ANSI code(s)

Raises:


136
137
138
139
140
# File 'lib/pastel/color.rb', line 136

def lookup(*colors)
  @cache.fetch(colors) do
    @cache[colors] = "\e[#{code(*colors).join(';')}m"
  end
end

#strip(*strings) ⇒ String

Strip ANSI color codes from a string.

Only ANSI color codes are removed, not movement codes or other escapes sequences are stripped.

Examples:

strip("foo\e[1mbar\e[0m")  # => "foobar"

Parameters:

  • strings (Array[String])

    a string or array of strings to sanitize

Returns:

  • (String)

103
104
105
106
# File 'lib/pastel/color.rb', line 103

def strip(*strings)
  modified = strings.map { |string| string.dup.gsub(ANSI_COLOR_REGEXP, "") }
  modified.size == 1 ? modified[0] : modified
end

#style_namesArray[Symbol]

List all available style names

Returns:

  • (Array[Symbol])

175
176
177
# File 'lib/pastel/color.rb', line 175

def style_names
  styles.keys
end

#stylesHash[Symbol]

Expose all ANSI color names and their codes

Returns:

  • (Hash[Symbol])

166
167
168
# File 'lib/pastel/color.rb', line 166

def styles
  ANSI::ATTRIBUTES.merge(ALIASES)
end

#valid?(*colors) ⇒ Boolean

Check if provided colors are known colors

Examples:

valid?(:red)   # => true

Parameters:

  • the (Array[Symbol,String])

    list of colors to check

Returns:

  • (Boolean)

    true if all colors are valid, false otherwise


191
192
193
# File 'lib/pastel/color.rb', line 191

def valid?(*colors)
  colors.all? { |color| style_names.include?(color.to_sym) }
end