Class: RackConsole::Ansi2Html

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_console/ansi2html.rb

Constant Summary collapse

SPAN_END =
"</span>".freeze
BR =
"<br/>".freeze
CLASS_FOR_CODE =
{
  0 => false,
  1 => :bold,
  2 => :faint,
  3 => :italic,
  4 => :underline,
  30 => :black,
  31 => :red,
  32 => :green,
  33 => :yellow,
  34 => :blue,
  35 => :magenta,
  36 => :cyan,
  37 => :white,
  40 => :bg_black,
  41 => :bg_red,
  42 => :bg_green,
  43 => :bg_yellow,
  44 => :bg_blue,
  45 => :bg_magenta,
  46 => :bg_cyan,
  47 => :bg_white,
}
@@tag_b =
{ }
@@tag_e =
{ }

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.convert(str, out = nil) ⇒ Object



8
9
10
# File 'lib/rack_console/ansi2html.rb', line 8

def self.convert str, out = nil
  new.convert(str, out)
end

Instance Method Details

#convert(str, out = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/rack_console/ansi2html.rb', line 12

def convert str, out = nil
  @str = str.dup
  @out = out || ''
  @tags = [ ]
  @out << %Q{<div class="ansi">}
  scan!
  tag_pop!
  @out << %Q{</div>}
  @out
end

#h(text) ⇒ Object



72
73
74
# File 'lib/rack_console/ansi2html.rb', line 72

def h(text)
  Rack::Utils.escape_html(text.to_s).gsub(' ', '&nbsp;')
end

#scan!Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack_console/ansi2html.rb', line 23

def scan!
  until @str.empty?
    case @str
    when /\A[^\e]+/
      text($&)
    when /\A\e\[([\d;]+)m/
      codes = $1.split(';').reject(&:empty?).map(&:to_i)
      codes.each do | code |
        cls = CLASS_FOR_CODE[code]
        tag(:span, cls) unless cls.nil?
      end
    when /\A.+/
      text($&)
    end
    @str = $'
  end
  self
end

#tag(name, cls) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rack_console/ansi2html.rb', line 42

def tag name, cls
  if cls
    tag_b =
      @@tag_b[[name, cls]] ||= %Q{<#{name} class="#{cls}">}.freeze
    tag_e =
      @@tag_e[name] ||= %Q{</#{name}>}.freeze
    @tags << [ tag_b, tag_e ]
    @out << tag_b
  else
    tag_pop!
  end
end

#tag_pop!Object



55
56
57
58
59
# File 'lib/rack_console/ansi2html.rb', line 55

def tag_pop!
  while tag_be = @tags.pop
    @out << tag_be[1]
  end
end

#text(str) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/rack_console/ansi2html.rb', line 61

def text str
  return if str.empty?
  lines = str.split("\n", 99999)
  last = lines.pop
  lines.each do | line |
    @out << h(line) unless line.empty?
    @out << BR
  end
  @out << h(last) unless last.empty?
end