Class: TermColor::MyListener

Inherits:
Object
  • Object
show all
Includes:
REXML::StreamListener
Defined in:
lib/termcolor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMyListener

Returns a new instance of MyListener.



70
71
72
73
# File 'lib/termcolor.rb', line 70

def initialize
  @result = ''
  @tag_stack = []
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



69
70
71
# File 'lib/termcolor.rb', line 69

def result
  @result
end

Instance Method Details

#tag_end(name) ⇒ Object



87
88
89
90
91
# File 'lib/termcolor.rb', line 87

def tag_end(name)
  @tag_stack.pop
  @result << HighLine::CLEAR
  @result << @tag_stack.map{|i| to_esc_seq(i)}.join unless @tag_stack.empty?
end

#tag_start(name, attrs) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/termcolor.rb', line 75

def tag_start(name, attrs)
  esc_seq = to_esc_seq(name)
  if esc_seq
    @result << esc_seq
    @tag_stack.push(name)
  end
end

#text(text) ⇒ Object



83
84
85
# File 'lib/termcolor.rb', line 83

def text(text)
  @result << CGI.unescapeHTML(text)
end

#to_esc_seq(name) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/termcolor.rb', line 93

def to_esc_seq(name)
  if (HighLine.const_defined?(name.upcase) rescue false)
    HighLine.const_get(name.upcase)
  else
    case name
    when /^([fb])(\d+)$/
      fb = $1 == 'f' ? 38 : 48
      color = $2.size == 3 ? 16 + $2.to_i(6) : 232 + $2.to_i
      "\e[#{fb};5;#{color}m"
    when /^[^0-9]?(\d+)$/
      "\e[#{$1}m"
    end
  end
end