Class: Col

Inherits:
Object
  • Object
show all
Defined in:
lib/col.rb,
lib/col/version.rb

Overview

————————————————————————— #

Defined Under Namespace

Classes: DB, Error, Formatter, Utils

Constant Summary collapse

COLORED_REGEXP =
/\e\[                             # opening character sequence
      (?: [34][0-7] | [0-9] ) ?   # optional code
  ( ; (?: [34][0-7] | [0-9] ))*   # more optional codes
 m                                # closing character
/x
VERSION =
"1.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Col

args: array of strings (to_s is called on each)



9
10
11
# File 'lib/col.rb', line 9

def initialize(*args)
  @strings = args.map { |a| a.to_s }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(message, *args, &block) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/col.rb', line 65

def method_missing(message, *args, &block)
  unless args.empty?
    super   # We're not interested in a message with arguments; NoMethodError
  end
  if Col::DB.method?(message)
    Col.new( self.fmt(message) )   # Col["..."].yellow -> Col
                                   #  to allow Col["..."].yellow.bold
  else
    self.fmt(message)              # Col["..."].gbow   -> String
  end
end

Class Method Details

.[](*args) ⇒ Object



13
14
15
# File 'lib/col.rb', line 13

def Col.[](*args)
  Col.new(*args)
end

.inline(*args) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/col.rb', line 35

def Col.inline(*args)
  unless args.size % 2 == 0    # even? breaks 1.8.6
    raise Col::Error, "Col.inline requires an even number of arguments"
  end
  result = String.new
  Col::Utils.each_pair(args) do |string, format|
    result << Col(string.to_s).fmt(format)
  end
  result
end

.plain(string) ⇒ Object

Convenience method to remove color codes from a string. Also available as Col.uncolored.



31
32
33
# File 'lib/col.rb', line 31

def Col.plain(string)
  string.gsub(COLORED_REGEXP, '')
end

.uncolored(string) ⇒ Object

Convenience method to remove color codes from a string. Also available as Col.plain.



25
26
27
# File 'lib/col.rb', line 25

def Col.uncolored(string)
  string.gsub(COLORED_REGEXP, '')
end

Instance Method Details

#fmt(*spec) ⇒ Object

e.g.

Col("one", "two", "three", "four").fmt "rb,y,cb,_b"
  # same as:
    "one".red.bold + "two".yellow + "three".cyan.bold + "four".bold

Col


52
53
54
# File 'lib/col.rb', line 52

def fmt(*spec)
  ::Col::Formatter.new(@strings, *spec).result
end

#to_sObject



56
57
58
# File 'lib/col.rb', line 56

def to_s
  @strings.join
end

#to_strObject

Works nicely with puts. E.g. puts Col(“…”).red.bold



61
62
63
# File 'lib/col.rb', line 61

def to_str
  to_s
end