Module: RSX::Escape

Defined in:
lib/rsx/escape.rb

Overview

HTML escaping. Runtime escaping goes through CGI.escapeHTML (a C extension in stdlib) so no third-party gem is needed.

Constant Summary collapse

ENTITY =

Matches a character reference such as & © or —

/&(?:[a-zA-Z][a-zA-Z0-9]{1,30}|#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});/

Class Method Summary collapse

Class Method Details

.attribute(value) ⇒ Object

Escapes a value destined for a double-quoted attribute.



51
52
53
54
55
56
57
# File 'lib/rsx/escape.rb', line 51

def attribute(value)
  return value if value.is_a?(SafeString)
  return CGI.escapeHTML(value) if value.instance_of?(String)
  return value.to_s if safe?(value)

  CGI.escapeHTML(value.to_s)
end

.html(string) ⇒ Object

Escapes text for element content or an attribute value.



15
16
17
# File 'lib/rsx/escape.rb', line 15

def html(string)
  CGI.escapeHTML(string)
end

.safe?(value) ⇒ Boolean

True for values that must not be escaped again.

ActiveSupport::SafeBuffer (what Rails helpers return) is a String subclass, so the exact-class check below is what keeps link_to output from being escaped while still taking the fast path for plain strings.

Returns:

  • (Boolean)


24
25
26
27
28
29
# File 'lib/rsx/escape.rb', line 24

def safe?(value)
  return true if value.is_a?(SafeString)
  return false if value.instance_of?(String)

  value.respond_to?(:html_safe?) && value.html_safe?
end

.static_text(string) ⇒ Object

Escaping for static text baked in at compile time.

JSX passes character references such as   through to the browser, so RSX keeps well-formed entities intact while still escaping stray markup.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rsx/escape.rb', line 35

def static_text(string)
  return CGI.escapeHTML(string) unless string.include?("&")

  out = +""
  last = 0
  string.scan(ENTITY) do
    match = Regexp.last_match
    out << CGI.escapeHTML(string[last...match.begin(0)])
    out << match[0]
    last = match.end(0)
  end
  out << CGI.escapeHTML(string[last..]) if last < string.length
  out
end