Skip to content

Instantly share code, notes, and snippets.

@joeyAghion
Last active April 8, 2018 02:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save joeyAghion/50ee54621a970976fb1c to your computer and use it in GitHub Desktop.
Save joeyAghion/50ee54621a970976fb1c to your computer and use it in GitHub Desktop.
# In gravity Rails console, for example.
url = app.reset_password_url(a: 'b', c: 'd')
# => "http://www.example.com/reset_password?a=b&c=d"
url.html_safe?
# => false
ERB::Util.h(url) # explicitly call the h() helper that's implicitly called by <%= ... %>
# => "http://www.example.com/reset_password?a=b&amp;c=d"
view = ActionView::Base.new('app/views', {}, ActionController::Base.new)
# => #<ActionView::Base:0x000000110c5a60 ...>
view.render(inline: "<html><body><%= url %></body></html>", locals: {url: url}) # encode implicitly
# => "<html><body>http://www.example.com/reset_password?a=b&amp;c=d</body></html>"
view.render(inline: "<html><body><%=h url %></body></html>", locals: {url: url}) # encode explicitly (same result)
# => "<html><body>http://www.example.com/reset_password?a=b&amp;c=d</body></html>"
view.render(inline: "<html><body><%= link_to 'test', url %></body></html>", locals: {url: url})
# => "<html><body><a href=\"http://www.example.com/reset_password?a=b&amp;c=d\">test</a></body></html>"
view.render(inline: "<html><body><%=raw url %></body></html>", locals: {url: url}) # explicitly allow unsafe HTML
# => "<html><body>http://www.example.com/reset_password?a=b&c=d</body></html>"
safe_url = url.html_safe # create a variable that's explicitly marked safe
# => "http://www.example.com/reset_password?a=b&c=d"
safe_url.html_safe?
# => true
safe_str = "&lt;html&rt;".html_safe # this string is known to be safe
# => "&lt;html&rt;"
safe_str.html_safe?
# => true
(url + safe_str).html_safe? # but when concatenated to an unsafe string, the result is unsafe
# => false
(safe_str + url).html_safe? # on the other hand, result of concatenating unsafe string to safe string is safe
# => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment