Module: Sentiero::Web::Escaping

Included in:
BaseApp, ScriptTag, ShareableReplay, Views::BaseView
Defined in:
lib/sentiero/web/escaping.rb

Overview

HTML and JavaScript escaping for safe template rendering using only stdlib.

Constant Summary collapse

HTML_UNSAFE_IN_SCRIPT =

Chars safe in JSON but unsafe in HTML breakout and HTML entity interpretation (mirrors ERB::Util.json_escape).

{
  "<" => '\u003c',
  ">" => '\u003e',
  "&" => '\u0026',
  "\u2028" => '\u2028',
  "\u2029" => '\u2029'
}.freeze
HTML_UNSAFE_IN_SCRIPT_PATTERN =
Regexp.union(HTML_UNSAFE_IN_SCRIPT.keys).freeze

Instance Method Summary collapse

Instance Method Details

#escape_html(text) ⇒ Object



22
23
24
# File 'lib/sentiero/web/escaping.rb', line 22

def escape_html(text)
  CGI.escapeHTML(text.to_s)
end

#escape_js_string(text) ⇒ Object

Escapes for embedding in a JS string literal; returns content WITHOUT surrounding quotes.



27
28
29
30
# File 'lib/sentiero/web/escaping.rb', line 27

def escape_js_string(text)
  json = JSON.generate(text.to_s)
  json[1..-2].gsub(HTML_UNSAFE_IN_SCRIPT_PATTERN, HTML_UNSAFE_IN_SCRIPT)
end

#escape_json(json_string) ⇒ Object



32
33
34
# File 'lib/sentiero/web/escaping.rb', line 32

def escape_json(json_string)
  json_string.gsub(HTML_UNSAFE_IN_SCRIPT_PATTERN, HTML_UNSAFE_IN_SCRIPT)
end