Read more

How to render an html_safe string escaped

Dominik Schöler
January 12, 2016Software engineer at makandra GmbH

Once Rails knows a given string is html_safe, it will never escape it. However, there may be times when you still need to escape it. Examples are some safe HTML that you pipe through JSON, or the display of an otherwise safe embed snippet.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

There is no semantically nice way to do this, as even raw and h do not escape html_safe strings (the former just marks its argument as html_safe). You need to turn your string into an unsafe string to get the escaping love from Rails:

embed = javascript_tag('var foo = 1337;') # This is an html_safe SafeBuffer
embed.to_str # This is a plain, unsafe String
Posted by Dominik Schöler to makandra dev (2016-01-12 09:24)