Module: Rubikon::ColoredIO

Defined in:
lib/rubikon/colored_io.rb

Overview

This module is used to enhance an IO stream to generate terminal color codes from simple text tags.

Author:

  • Sebastian Staudt

Since:

  • 0.5.0

Constant Summary collapse

COLORS =

Color codes that can be used inside a IO enhanced with ColoredIO

Since:

  • 0.5.0

{
  :black  => 30,
  :bl     => 30,
  :red    => 31,
  :r      => 31,
  :green  => 32,
  :g      => 32,
  :yellow => 33,
  :y      => 33,
  :blue   => 34,
  :b      => 34,
  :purple => 35,
  :p      => 35,
  :cyan   => 37,
  :c      => 36,
  :white  => 37,
  :w      => 37,
}
COLOR_MATCHER =

The keys of the color codes joined for the regular expression

Since:

  • 0.5.0

COLORS.keys.join('|')

Class Method Summary collapse

Class Method Details

.add_color_filter(io, enabled = true) ⇒ Object

Enables color filtering on the given output stream (or another object responding to puts)

This wraps the IO’s puts method into a call to color_filter. The color_filter method is added dynamically to the singleton class of the object and does either turn color tags given to the output stream into their corresponding color code or it simply removes the color tags, if coloring is disabled.

Parameters:

  • io (IO)

    The IO object to add color filtering to

Raises:

  • TypeError if the given object does not respond to puts

See Also:

Since:

  • 0.5.0



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rubikon/colored_io.rb', line 50

def self.add_color_filter(io, enabled = true)
  raise TypeError unless io.respond_to? :puts
  return if io.respond_to?(:color_filter)

  enabled = enabled && ENV['TERM'] != 'dumb'
  if enabled && RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin/
    begin
      require 'Win32/Console/ANSI'
    rescue LoadError 
      enabled = false
    end
  end

  class << io
    const_set :COLORS, COLORS

    def puts(text = '')
      self.class.
        instance_method(:puts).bind(self).call color_filter(text.to_s)
    end
  end

  if enabled
    class << io
      def color_filter(text)
        text.gsub(/(#{COLOR_MATCHER})\{(.*?)\}/i) do
          "\e[0;#{COLORS[$1.downcase.to_sym]}m#{$2}\e[0m"
        end
      end
    end
  else
    class << io
      def color_filter(text)
        text.gsub(/(#{COLOR_MATCHER})\{(.*?)\}/i, '\2')
      end
    end
  end
end

.remove_color_filter(io) ⇒ Object

Disables color filtering on the given output stream

This reverts the actions of add_color_filter

Parameters:

  • io (IO)

    The IO object to remove color filtering from

See Also:

Since:

  • 0.5.0



95
96
97
98
99
100
101
102
# File 'lib/rubikon/colored_io.rb', line 95

def self.remove_color_filter(io)
  return unless io.respond_to?(:color_filter)
  class << io
    remove_const  :COLORS
    remove_method :color_filter
    remove_method :puts
  end
end