Module: Hanami::Utils::ShellColor

Defined in:
lib/hanami/utils/shell_color.rb

Overview

Shell helper for colorizing STDOUT

It doesn’t check if you’re writing to a file or anything, so you have to check that yourself before using this module.

Since:

  • 1.2.0

Defined Under Namespace

Classes: UnknownColorCodeError

Constant Summary collapse

COLORS =

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

Escapes codes for terminals to output strings in colors

Since:

  • 1.2.0

::Hash[
  black: 30,
  red: 31,
  green: 32,
  yellow: 33,
  blue: 34,
  magenta: 35,
  cyan: 36,
  gray: 37,
].freeze

Class Method Summary collapse

Class Method Details

.call(input, color:) ⇒ String

Colorizes output 8 colors available: black, red, green, yellow, blue, magenta, cyan, and gray

Parameters:

  • input (#to_s)

    the string to colorize

  • color (Symbol)

    the color

Returns:

  • (String)

    the colorized string

Raises:

  • (Hanami::Utils::ShellColor::UnknownColorError)

    if the color code is unknown

Since:

  • 1.2.0



52
53
54
# File 'lib/hanami/utils/shell_color.rb', line 52

def self.call(input, color:)
  "\e[#{color_code(color)}m#{input}\e[0m"
end

.color_code(code) ⇒ Object

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.

Helper method to translate between color names and terminal escape codes

Raises:

  • (Hanami::Utils::ShellColor::UnknownColorError)

    if the color code is unknown

Since:

  • 1.2.0



63
64
65
# File 'lib/hanami/utils/shell_color.rb', line 63

def self.color_code(code)
  COLORS.fetch(code) { raise UnknownColorCodeError.new(code) }
end