Rails 6 preserves status of #html_safe?

Vishal Telangre

Vishal Telangre

August 13, 2019

This blog is part of our  Rails 6 series.

Before Rails 6

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

1>> html_content = "<div>Hello, world!</div>".html_safe
2# => "<div>Hello, world!</div>"
3>> html_content.html_safe?
4# => true
5>> html_content[0..-1].html_safe?
6# => nil

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

1>> line_break = "<br />".html_safe
2# => "<br />"
3>> line_break.html_safe?
4# => true
5>> two_line_breaks = (line_break * 2)
6# => "<br /><br />"
7>> two_line_breaks.html_safe?
8# => 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.

1>> html_content = "<div>Hello, world!</div>".html_safe
2# => "<div>Hello, world!</div>"
3>> html_content.html_safe?
4# => true
5>> html_content[0..-1].html_safe?
6# => true
7
8>> line_break = "<br />".html_safe
9# => "<br />"
10>> line_break.html_safe?
11# => true
12>> two_line_breaks = (line_break * 2)
13# => "<br /><br />"
14>> two_line_breaks.html_safe?
15# => true

Please check rails/rails#33808 and rails/rails#36012 for the relevant changes.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.