Skip to content

Instantly share code, notes, and snippets.

@iax7
Last active December 30, 2023 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iax7/9895052e4a72ad736064140b710323d0 to your computer and use it in GitHub Desktop.
Save iax7/9895052e4a72ad736064140b710323d0 to your computer and use it in GitHub Desktop.
Simple class to generate ANSI Color output
# @example basic usage
# Color.blue => "\e[1;34m"
# @example chain bold
# Color.red.bold => "\e[1;31m"
class Color
NORMAL = 30
BRIGHT = 90
BG_DIFF = 10
CODES = {
black: 0,
red: 1,
green: 2,
yellow: 3,
blue: 4,
magenta: 5,
cyan: 6,
white: 7
}.freeze
def initialize(code)
@code = code
@modifier = nil
end
def bold
@modifier = 1
self
end
def to_s
modifier = @modifier ? "#{@modifier};" : '' unless @code.zero?
"\e[#{modifier}#{@code}m"
end
def inspect
"<#{self.class} code=#{@code} mod=#{@modifier.inspect}>"
end
define_singleton_method(:reset) { new 0 }
CODES.each do |color, code|
define_singleton_method(color) { new(code + NORMAL) }
define_singleton_method("bright_#{color}") { new(code + BRIGHT) }
define_singleton_method("bg_#{color}") { new(code + NORMAL + BG_DIFF) }
define_singleton_method("bg_bright_#{color}") { new(code + BRIGHT + BG_DIFF) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment