Sha256: 825a873d92b0065e8af541834049312d96771f1305a9de5cc316cee8f1875b06

Contents?: true

Size: 1.68 KB

Versions: 9

Compression:

Stored size: 1.68 KB

Contents

require "rbconfig"

# Mix in to your Mothership class to enable user-toggleable colors.
#
# Redefine color_enabled? to control color enabling/disabling. Colors will be
# auto-disabled if the platform is Windows or if $stdout is not a tty.
#
# Redefine user_colors to return a hash from tags to color, e.g. from a user's
# color config file.
module Mothership::Pretty
  WINDOWS = !!(RbConfig::CONFIG['host_os'] =~ /mingw|mswin32|cygwin/)

  COLOR_CODES = {
    :black => 0,
    :red => 1,
    :green => 2,
    :yellow => 3,
    :blue => 4,
    :magenta => 5,
    :cyan => 6,
    :white => 7
  }

  DEFAULT_COLORS = {
    :name => :blue,
    :neutral => :blue,
    :good => :green,
    :bad => :red,
    :error => :magenta,
    :unknown => :cyan,
    :warning => :yellow,
    :instance => :yellow,
    :number => :green,
    :prompt => :blue,
    :yes => :green,
    :no => :red,
    :dim => :black,
    :default => :black
  }

  private

  # override with e.g. option(:color), or whatever toggle you use
  def color_enabled?
    true
  end

  # use colors?
  def color?
    color_enabled? && !WINDOWS && $stdout.tty?
  end

  # redefine to control the tag -> color settings
  def user_colors
    DEFAULT_COLORS
  end

  # colored text
  #
  # shouldn't use bright colors, as some color themes abuse
  # the bright palette (I'm looking at you, Solarized)
  def c(str, type)
    return str unless color?

    bright = false
    color = user_colors[type]
    if color =~ /bright-(.+)/
      bright = true
      color = $1.to_sym
    end

    return str unless color

    "\e[#{bright ? 9 : 3}#{COLOR_CODES[color]}m#{str}\e[0m"
  end

  # bold text
  def b(str)
    return str unless color?
    "\e[1m#{str}\e[0m"
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
mothership-0.0.9 lib/mothership/pretty.rb
mothership-0.0.8 lib/mothership/pretty.rb
mothership-0.0.7 lib/mothership/pretty.rb
mothership-0.0.6 lib/mothership/pretty.rb
mothership-0.0.5 lib/mothership/pretty.rb
mothership-0.0.4 lib/mothership/pretty.rb
mothership-0.0.3 lib/mothership/pretty.rb
mothership-0.0.2 lib/mothership/pretty.rb
mothership-0.0.1 lib/mothership/pretty.rb