Sha256: 7695f2cb648034643409c32cf0c9fabd114be747c6b278da43e13bb4ec1f2c21

Contents?: true

Size: 1.17 KB

Versions: 3

Compression:

Stored size: 1.17 KB

Contents

module Boom
  # Color collects some methods for colorizing terminal output.
  module Color
    extend self

    CODES = {
      :reset   => "\e[0m",

      :cyan    => "\e[36m",
      :magenta => "\e[35m",
      :red     => "\e[31m",
      :yellow  => "\e[33m"
    }

    # Tries to enable Windows support if on that platform.
    #
    # Returns nothing.
    def self.included(other)
      if RUBY_PLATFORM =~ /win32/ || RUBY_PLATFORM =~ /mingw32/
        require 'Win32/Console/ANSI'
      end
    rescue LoadError
      # Oh well, we tried.
    end

    # Wraps the given string in ANSI color codes
    #
    # string     - The String to wrap.
    # color_code - The String representing he ANSI color code
    #
    # Examples
    #
    #   colorize("Boom!", :magenta)
    #   # => "\e[35mBoom!\e[0m"
    #
    # Returns the wrapped String.
    def colorize(string, color_code)
      "#{CODES[color_code] || color_code}#{string}#{CODES[:reset]}"
    end

    # Set up shortcut methods to all the codes define in CODES.
    self.class_eval(CODES.keys.reject {|color| color == :reset }.map do |color|
      "def #{color}(string); colorize(string, :#{color}); end"
    end.join("\n"))
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
boom-0.2.3 lib/boom/color.rb
boom-0.2.2 lib/boom/color.rb
boom-0.2.1 lib/boom/color.rb