skip to content

In Rails views, what does String#html_safe actually do, and how do raw and <%== %> relate to it and to SafeBuffer?

level: middleimportance: must knowfreq 62%

answer

  1. a label, not a filter
  2. ActiveSupport::SafeBuffer
  3. raw(x) is x.to_s.html_safe
  4. <%== %> appends without escaping
  5. interpolate first, trust everything

basics

~10 s

In Rails, String#html_safe wraps the string in an ActiveSupport::SafeBuffer marked trusted, without escaping or cleaning anything. raw(x) is x.to_s.html_safe, and <%== %> appends a value unescaped; all three only switch escaping off.

solid answer

~30 s

`html_safe` returns an `ActiveSupport::SafeBuffer` with the same characters and `html_safe?` true; it does not inspect or change the text. When a template prints it with `<%= %>`, the buffer sees the flag and skips `ERB::Util.html_escape`. `raw(x)` is the helper form, `x.to_s.html_safe`, so it also tolerates `nil`, while `nil.html_safe` raises `NoMethodError`. `<%== x %>` appends `x` without the escaping check at all. None of them makes user text safe: `"<p>#{@member.bio}</p>".html_safe` trusts the bio along with your own tags. Build markup with helpers such as `tag.p(@member.bio)` or `safe_join`, which escape their arguments, and use `sanitize` when users may submit a few formatting tags.

code

ruby · 12 lines
ruby
bio = "<script>alert(1)</script>"

bio.html_safe?                 # => false
safe = bio.html_safe
safe.class                     # => ActiveSupport::SafeBuffer
safe.html_safe?                # => true
safe == bio                    # => true (same characters)

raw(nil)                       # => "" (html_safe)
# nil.html_safe               # NoMethodError

tag.p(bio)                     # => "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"

go deeper

for a junior

Remember that html_safe and raw switch escaping off rather than adding it, and should not be used on user input.

for a middle

Explain SafeBuffer and the html_safe? check at output time, the nil difference between raw and html_safe, and the interpolation trap with its helper-based fixes.

for a senior

Review helpers for strings built by interpolation and then trusted, replace them with tag helpers or safe_join, and require a written reason for each remaining opt-out.

for a principal

Decide where trusted HTML may enter the system, such as one sanitising boundary for rich text, so most code never needs to make a trust claim.

## Escaping is decided by a flag Rails escapes view output by default. The decision is made per value: when `<%= %>` appends something, Action View's output buffer asks `html_safe?`. A plain `String` answers `false` and is passed through `ERB::Util.html_escape`; an **`ActiveSupport::SafeBuffer`** answers `true` (until something marks it unsafe) and is appended as-is. Everything that turns escaping off works by producing a SafeBuffer or by skipping the check. ## The three opt-outs | Form | What it is | `nil` input | Typical place | |---|---|---|---| | `str.html_safe` | `String` method from Active Support; returns `SafeBuffer.new(str)` | raises `NoMethodError` (`nil` has no `html_safe`) | helpers that build markup from trusted literals | | `raw(x)` | Action View helper, `x.to_s.html_safe` | returns an empty safe string | a template that prints trusted markup | | `<%== x %>` | ERB tag compiled to `safe_expr_append=` | prints nothing | rare; the same as `<%= raw(x) %>` | Key properties shared by all three: - **No transformation.** The characters are not escaped, stripped or validated. `"<script>".html_safe` is still a script tag; it is now also trusted. - **The flag travels with the object.** Store a SafeBuffer in a variable, pass it to another helper, and it stays trusted. - **Responsibility moves to you.** Active Support's own documentation for `html_safe` says it should never be called on user input and recommends `sanitize` instead. ## The interpolation trap The most common real bug is marking a whole string safe after building it: ```ruby # app/helpers/profiles_helper.rb def bio_paragraph(member) "<p class=\"bio\">#{member.bio}</p>".html_safe # XSS: the bio is trusted too end ``` Interpolation happens first, so the member's text becomes part of the trusted string. Three safe rewrites: 1. `tag.p(member.bio, class: "bio")`: tag helpers escape their content and attributes and return a SafeBuffer. 2. `safe_join([tag.strong(member.display_name), member.bio], " ")`: each non-safe element and the separator are escaped, and the joined result is marked safe. 3. `"<p>".html_safe + member.bio + "</p>".html_safe`: `SafeBuffer#+` escapes an unsafe argument before concatenating. It works, but helpers read better. ## Where trusted values come from Most SafeBuffers in a view were made by Rails, not by hand: - tag and link helpers such as `tag.p`, `content_tag` and `link_to`, which escape what they wrap; - the output of `render`, so a partial's HTML is appended unescaped into its parent; - `sanitize` and `strip_tags`, which return their cleaned output marked safe; - `safe_join` and `raw`; - numbers, because `Numeric#html_safe?` returns true. Because these sources are safe by construction, a view that sticks to them never needs an explicit `html_safe`. ## When raw markup is legitimate - Markup you wrote yourself, for example an inline SVG icon kept in a constant. - Output of a library that already produced escaped HTML but returns it as a plain String; Pagy 43's navigation helpers do this, and its documentation prints them with `<%== %>`. - User-submitted rich text after `sanitize` has removed everything outside an allowlist. `sanitize` already returns a SafeBuffer, so it needs no `raw` around it. In each case the reason belongs in a comment next to the call, because a reviewer cannot tell trusted from untrusted input by looking at the method name. ## How to explain it in an interview A good one-line model: **escaping happens at output time, and `html_safe` is a claim that the value needs none.** Helpers keep that claim honest by escaping whatever they wrap. Calling `html_safe` on anything that contains user input, directly or through interpolation, makes the claim false, and Rails has no second line of defence inside the template.

  • Why is `<%= sanitize @member.bio %>` correct without `raw` around it?
    `sanitize` removes tags and attributes outside its allowlist and returns the result already marked `html_safe`, so `<%= %>` appends it without escaping. Wrapping it in `raw` adds nothing; wrapping the original bio in `raw` instead would skip the cleaning entirely.
  • How would you find risky opt-outs in an existing Rails codebase?
    Search templates and helpers for `html_safe`, `raw(` and `<%==`, then check whether each value could contain user input, including through interpolation. Brakeman flags many of these cases too. Each surviving call should carry a comment saying why the value is trusted.
  • Is `safe_join` just `join(...).html_safe`?
    No. `safe_join` flattens the array, escapes every element and the separator that is not already html_safe, joins them and only then marks the result safe. `join(...).html_safe` would trust every element, including user text.

html_safe is a "security checked" sticker on a parcel: the sticker makes the guards wave it through, but sticking it on inspects nothing. Only a real scan, like sanitize or a tag helper escaping its contents, makes the sticker true.

  • html_safe escapes the string so it is safe to print.
  • raw cleans dangerous tags out before printing the value.
  • <%== %> is a stricter variant of <%= %> that escapes more characters.
  • Interpolating user text then calling html_safe is fine when the outer tags are ours.
  • safe_join simply joins the array and marks the result html_safe.