module Corefines::String::Color
@!method color
@example "Roses are red".color(:red) # => "\e[0;31;49mRoses are red\e[0m" "Roses are red".color(text: :red, mode: :bold) # => "\e[1;31;49mRoses are red\e[0m" "Violets are blue".color(background: 'blue') # => "\e[0;39;44mViolets are blue\e[0m" "Sugar is sweet".color(text: 7) # => "\e[0;37;49mSugar is sweet\e[0m" @overload color(text_color) @param text_color [#to_sym, Integer] text (foreground) color (see {COLOR_CODES}). @overload color(opts) @option opts [#to_sym, Integer] :mode text attributes (see {MODE_CODES}). @option opts [#to_sym, Integer] :text,:fg text (foreground) color (see {COLOR_CODES}). @option opts [#to_sym, Integer] :background,:bg background color (see {COLOR_CODES}). @return [String] a copy of this string colored for command line output using ANSI escape codes. @see Decolor#decolor
Constants
- COLOR_CODES
- MODE_CODES
Private Class Methods
color_code(color, offset)
click to toggle source
# File lib/corefines/string.rb, line 135 def self.color_code(color, offset) return color + offset if color.is_a? ::Integer COLOR_CODES[color.to_sym] + offset if color && COLOR_CODES[color.to_sym] end
mode_code(mode)
click to toggle source
# File lib/corefines/string.rb, line 140 def self.mode_code(mode) return mode if mode.is_a? ::Integer MODE_CODES[mode.to_sym] if mode end
Public Instance Methods
color(opts)
click to toggle source
# File lib/corefines/string.rb, line 117 def color(opts) opts = {text: opts} unless opts.is_a? ::Hash opts[:fg] ||= opts[:text] || opts[:color] opts[:bg] ||= opts[:background] scan(ESCAPE_SEQUENCE).reduce('') do |str, match| mode = Color.mode_code(opts[:mode]) || match[0] || 0 fg_color = Color.color_code(opts[:fg], 30) || match[1] || 39 bg_color = Color.color_code(opts[:bg], 40) || match[2] || 49 text = match[3] || match[4] str << "\033[#{mode};#{fg_color};#{bg_color}m#{text}\033[0m" end end