Class: Polytrix::Util::HTML

Inherits:
Object
  • Object
show all
Defined in:
lib/polytrix/util.rb

Constant Summary collapse

ANSICODES =
{
  '1' => 'bold',
  '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'
}
ESCAPE_HTML =

From Rack

{
  '&' => '&',
  '<' => '&lt;',
  '>' => '&gt;',
  "'" => '&#x27;',
  '"' => '&quot;',
  '/' => '&#x2F;'
}
ESCAPE_HTML_PATTERN =
Regexp.union(*ESCAPE_HTML.keys)

Class Method Summary collapse

Class Method Details

.escape_html(string) ⇒ Object

Escape ampersands, brackets and quotes to their HTML/XML entities.



189
190
191
# File 'lib/polytrix/util.rb', line 189

def self.escape_html(string)
  string.to_s.gsub(ESCAPE_HTML_PATTERN) { |c| ESCAPE_HTML[c] }
end

.from_ansi(text) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/polytrix/util.rb', line 159

def self.from_ansi(text)
  ansi = StringScanner.new(text)
  html = StringIO.new
  until ansi.eos?
    if ansi.scan(/\e\[0?m/)
      html.print(%(</span>))
    elsif ansi.scan(/\e\[0?(\d+)m/)
      # use class instead of style?
      style = ANSICODES[ansi[1]] || 'text-reset'
      html.print(%(<span class="#{style}">))
    else
      html.print(ansi.scan(/./m))
    end
  end
  html.string
end