Skip to content

Instantly share code, notes, and snippets.

@awesome
Created December 4, 2020 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/5f012f4483418f09bf240a3d5ab18005 to your computer and use it in GitHub Desktop.
Save awesome/5f012f4483418f09bf240a3d5ab18005 to your computer and use it in GitHub Desktop.
2020 ERB escape and text-transformation
##
# Using Text Transformation Methods
#
# ERB provides optional methods for transforming text.
# To use these features your code must include the module ERB::Util.
# via "An Introduction to ERB templating" (July 01, 2016) https://www.stuartellis.name/articles/erb/#using-text-transformation-methods-
#
# ERB transformation has changed since 2016: "j" not defined as alias but still executes without error, albiet weird rendering
# https://api.rubyonrails.org/classes/ERB/Util.html#method-c-json_escape
#
require 'erb'
# HTML
# https://api.rubyonrails.org/classes/ERB/Util.html#method-i-h
@html_string = 'is a > 0 & a < 10?'
template_with_html_example = "HTML: <%= h(@html_string) %>"
puts ERB.new(template_with_html_example).result
# => "HTML: is a &gt; 0 &amp; a &lt; 10?"
# JSON (weird output; parses json first to STDOUT before result)
# https://api.rubyonrails.org/classes/ERB/Util.html#method-c-json_escape
require 'json'
@json_string = JSON.generate({name: "</script><script>alert('PWNED!!!')</script>"})
# => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
template_with_json_example = "JSON: <%= j(@json_string) %>"
puts ERB.new(template_with_json_example).result
# "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
# => "JSON: "
#
# TODO
#
#
# # Textile
# @textile_string = x
# template_with_textile_example = "TEXTILE: <%= t(@textile_string) %>"
#
# # URL encoded:
# @url_string = x
# template_with_url_example = "URL: <%= u(@url_string) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment