module ZTK::ANSI

ANSI Mixin Module

Standard use is to mix this module into String.

@example Mix this module into String to enable easy ANSI coloring methods like:

"bold red".red.bold

@example Or

"green".green

@author Zachary Patten <zpatten AT jovelabs DOT io>

Constants

ANSI_ATTRIBUTES

Defines our ANSI attribute codes

ANSI_COLORS

Defines our ANSI color codes

ANSI_REGEX

Defines a RegEx for stripping ANSI codes from strings

Public Instance Methods

build_ansi_methods(hash) click to toggle source

Build ANSI Methods

Dynamicly constructs our color methods based on the ANSI code hash passed in.

@param [Hash] hash A hash where the keys represent the method names and

the values are the ANSI codes.

@return [Boolean] True if successful.

# File lib/ztk/ansi.rb, line 110
def build_ansi_methods(hash)
  hash.each do |key, value|

    define_method(key) do |string=nil, &block|
      result = Array.new

      result << %(\e[#{value}m)
      if block_given?
        result << block.call
      elsif string.respond_to?(:to_str)
        result << string.to_str
      elsif respond_to?(:to_str)
        result << to_str
      else
        return result
      end
      result << %(\e[0m)

      result.join
    end

  end

  true
end
goto(x=0, y=0) click to toggle source
# File lib/ztk/ansi.rb, line 172
def goto(x=0, y=0)
  %(\e[#{x};#{y}H)
end
reset(string=nil, &block) click to toggle source
# File lib/ztk/ansi.rb, line 155
def reset(string=nil, &block)
  result = Array.new

  result << %(\e[2J)
  if block_given?
    result << block.call
  elsif string.respond_to?(:to_str)
    result << string.to_str
  elsif respond_to?(:to_str)
    result << to_str
  else
    return result
  end

  result.join
end
uncolor(string=nil, &block) click to toggle source

Uncolor String

Removes ANSI code sequences from a string.

@param [String] string The string to operate on. @yieldreturn [String] The string to operate on. @return [String] The supplied string stripped of ANSI codes.

# File lib/ztk/ansi.rb, line 143
def uncolor(string=nil, &block)
  if block_given?
    block.call.to_str.gsub(ANSI_REGEX, '')
  elsif string.respond_to?(:to_str)
    string.to_str.gsub(ANSI_REGEX, '')
  elsif respond_to?(:to_str)
    to_str.gsub(ANSI_REGEX, '')
  else
    ''
  end
end