class RackConsole::Ansi2Html

Constants

BR
CLASS_FOR_CODE

en.wikipedia.org/wiki/ANSI_escape_code

SPAN_END

Public Class Methods

convert(str, out = nil) click to toggle source
# File lib/rack_console/ansi2html.rb, line 7
def self.convert str, out = nil
  new.convert(str, out)
end

Public Instance Methods

convert(str, out = nil) click to toggle source
# File lib/rack_console/ansi2html.rb, line 11
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) click to toggle source
# File lib/rack_console/ansi2html.rb, line 73
def h(text)
  Rack::Utils.escape_html(text.to_s).gsub(' ', '&nbsp;')
end
scan!() click to toggle source
# File lib/rack_console/ansi2html.rb, line 22
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) click to toggle source
# File lib/rack_console/ansi2html.rb, line 41
def tag name, cls
  if cls
    tag_be =
      (@@tag_cache[name] ||= { })[cls] ||=
      [
      %Q{<#{name} class="#{cls}">}.freeze,
      %Q{</#{name}>}.freeze,
      ].freeze
    @tags << tag_be
    @out  << tag_be[0]
  else
    tag_pop!
  end
end
tag_pop!() click to toggle source
# File lib/rack_console/ansi2html.rb, line 56
def tag_pop!
  while tag_be = @tags.pop
    @out << tag_be[1]
  end
end
text(str) click to toggle source
# File lib/rack_console/ansi2html.rb, line 62
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