---
title: "Rails 6 preserves status of #html_safe?"
description:
  '"Rails 6 preserves status of #html_safe? on HTML safe strings which are
  sliced or multiplied using `ActiveSupport::SafeBuffer#*`"'
canonical_url: "https://www.bigbinary.com/blog/rails-6-preserves-status-of-html_safe-on-sliced-and-multiplied-html-safe-strings"
markdown_url: "https://www.bigbinary.com/blog/rails-6-preserves-status-of-html_safe-on-sliced-and-multiplied-html-safe-strings.md"
---

# Rails 6 preserves status of #html_safe?

"Rails 6 preserves status of #html_safe? on HTML safe strings which are sliced
or multiplied using `ActiveSupport::SafeBuffer#*`"

- Author: Vishal Telangre
- Published: August 13, 2019
- Categories: Rails 6, Rails

## Before Rails 6

Before Rails 6, calling `#html_safe?` on a slice of an HTML safe string returns
`nil`.

```ruby
>> html_content = "<div>Hello, world!</div>".html_safe
# => "<div>Hello, world!</div>"
>> html_content.html_safe?
# => true
>> html_content[0..-1].html_safe?
# => nil
```

Also, before Rails 6, the `ActiveSupport::SafeBuffer#*` method does not preserve
the HTML safe status as well.

```ruby
>> line_break = "<br />".html_safe
# => "<br />"
>> line_break.html_safe?
# => true
>> two_line_breaks = (line_break * 2)
# => "<br /><br />"
>> two_line_breaks.html_safe?
# => nil
```

## Rails 6 returns expected status of `#html_safe?`

In Rails 6, both of the above cases have been fixed properly.

Therefore, we will now get the status of `#html_safe?` as expected.

```ruby
>> html_content = "<div>Hello, world!</div>".html_safe
# => "<div>Hello, world!</div>"
>> html_content.html_safe?
# => true
>> html_content[0..-1].html_safe?
# => true

>> line_break = "<br />".html_safe
# => "<br />"
>> line_break.html_safe?
# => true
>> two_line_breaks = (line_break * 2)
# => "<br /><br />"
>> two_line_breaks.html_safe?
# => true
```

Please check [rails/rails#33808](https://github.com/rails/rails/pull/33808) and
[rails/rails#36012](https://github.com/rails/rails/pull/36012) for the relevant
changes.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-preserves-status-of-html_safe-on-sliced-and-multiplied-html-safe-strings)
