Sha256: 6b201904009fbf061727dc224beb7f3c40b3f9bb82026b41f5d361ea93acaee9

Contents?: true

Size: 1.43 KB

Versions: 3

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

module Strings
  # Helper functions for handling ANSI escape sequences
  module ANSI
    # The control sequence indicator
    CSI = "\033".freeze

    # The code for reseting styling
    RESET = "\e[0m".freeze

    # The regex to match ANSI codes
    ANSI_MATCHER = '(\[)?\033(\[)?[;?\d]*[\dA-Za-z]([\];])?'.freeze

    # Remove ANSI characters from the text
    #
    # @param [String] text
    #
    # @example
    #   Strings::ANSI.sanitize("\e[33mfoo\[e0m")
    #   # => "foo"
    #
    # @return [String]
    #
    # @api public
    def sanitize(text)
      text.gsub(/#{ANSI_MATCHER}/, '')
    end
    module_function :sanitize

    # 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
    def ansi?(string)
      !!(string =~ /#{ANSI_MATCHER}/)
    end
    module_function :ansi?

    # 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
    def only_ansi?(string)
      !!(string =~ /^#{ANSI_MATCHER}$/)
    end
    module_function :only_ansi?
  end # Sanitizer
end # Strings

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
strings-0.1.2 lib/strings/ansi.rb
strings-0.1.1 lib/strings/ansi.rb
strings-0.1.0 lib/strings/ansi.rb