module Strings::ANSI

Helper functions for handling ANSI escape sequences

Constants

ANSI_MATCHER

The regex to match ANSI codes

CSI

The control sequence indicator

RESET

The code for reseting styling

VERSION

Public Class Methods

ansi?(string) click to toggle source

Check if string contains ANSI codes

@param [String] string

the string to check

@example

Strings::ANSI.ansi?("\e[33mfoo\[e0m")
# => true

@return [Boolean]

@api public

# File lib/strings/ansi.rb, line 45
def ansi?(string)
  !!(string =~ /#{ANSI_MATCHER}/)
end
only_ansi?(string) click to toggle source

Check if string contains only ANSI codes

@param [String] string

the string to check

@example

Strings::ANSI.only_ansi?("\e[33mfoo\[e0m")
# => false

Strings::ANSI.only_ansi?("\e[33m")
# => false

@return [Boolean]

@api public

# File lib/strings/ansi.rb, line 65
def only_ansi?(string)
  !!(string =~ /^(#{ANSI_MATCHER})+$/)
end
sanitize(string) click to toggle source

Return a copy of string with ANSI characters removed

@param [String] string

@example

Strings::ANSI.sanitize("\e[33mfoo\[e0m")
# => "foo"

@return [String]

@api public

# File lib/strings/ansi.rb, line 28
def sanitize(string)
  string.gsub(/#{ANSI_MATCHER}/, '')
end

Private Instance Methods

ansi?(string) click to toggle source

Check if string contains ANSI codes

@param [String] string

the string to check

@example

Strings::ANSI.ansi?("\e[33mfoo\[e0m")
# => true

@return [Boolean]

@api public

# File lib/strings/ansi.rb, line 45
def ansi?(string)
  !!(string =~ /#{ANSI_MATCHER}/)
end
only_ansi?(string) click to toggle source

Check if string contains only ANSI codes

@param [String] string

the string to check

@example

Strings::ANSI.only_ansi?("\e[33mfoo\[e0m")
# => false

Strings::ANSI.only_ansi?("\e[33m")
# => false

@return [Boolean]

@api public

# File lib/strings/ansi.rb, line 65
def only_ansi?(string)
  !!(string =~ /^(#{ANSI_MATCHER})+$/)
end
sanitize(string) click to toggle source

Return a copy of string with ANSI characters removed

@param [String] string

@example

Strings::ANSI.sanitize("\e[33mfoo\[e0m")
# => "foo"

@return [String]

@api public

# File lib/strings/ansi.rb, line 28
def sanitize(string)
  string.gsub(/#{ANSI_MATCHER}/, '')
end