Module: TermColor

Includes:
REXML
Defined in:
lib/termcolor.rb

Defined Under Namespace

Classes: MyListener

Constant Summary collapse

VERSION =
'1.2.2'

Class Method Summary collapse

Class Method Details

.colorize(text, color) ⇒ Object



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

def colorize(text, color)
  parse("<#{color}>#{escape(text)}</#{color}>")
end

.escape(text) ⇒ Object



20
21
22
# File 'lib/termcolor.rb', line 20

def escape(text)
  escape_or_unescape(:escape, text)
end

.escape_or_unescape(dir = :escape, text) ⇒ Object



28
29
30
31
32
# File 'lib/termcolor.rb', line 28

def escape_or_unescape(dir=:escape, text)
  h = Hash[*%w(& &amp; < &lt; > &gt; ' &apos; " &quot;)]
  h = h.invert if dir == :unescape
  text.gsub(/(#{h.keys.join('|')})/){ h[$1] }
end

.parse(text) ⇒ Object



14
15
16
17
18
# File 'lib/termcolor.rb', line 14

def parse(text)
  listener = MyListener.new 
  REXML::Parsers::StreamParser.new(prepare_parse(text), listener).parse
  listener.result
end

.prepare_parse(text) ⇒ Object



35
36
37
# File 'lib/termcolor.rb', line 35

def prepare_parse(text)
  tag_separate text.gsub(/<(\/?)(\d+)>/, '<\1_\2>')
end

.tag_separate(text) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/termcolor.rb', line 39

def tag_separate(text)
  re = /<(\/*)([^\W_]+)(?:_(on_[^\W_]+))*(?:_with_([^\W_]+))*(?:_and_([^\W_]+))*>/
  text.gsub(re) do
    matchs = $~.captures
    if matchs.shift.empty?
      tag = ->t{ "<#{t}>" }
    else
      matchs.reverse!
      tag = ->t{ "</#{t}>" }
    end
    matchs.compact.map { |word| tag[word] }.join
  end
end

.test(*args) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/termcolor.rb', line 53

def test(*args)
  args = (0..109).to_a if args.empty?
  args.each_with_index do |color, index|
    print parse("<#{color}> #{color} </#{color}>") + "\t"
    puts if (index + 1) % 10 == 0
  end
end

.unescape(text) ⇒ Object



24
25
26
# File 'lib/termcolor.rb', line 24

def unescape(text)
  escape_or_unescape(:unescape, text)
end