August 13, 2019
This blog is part of our Rails 6 series.
Before Rails 6, calling #html_safe?
on a slice of an HTML safe string returns
nil
.
>> 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.
>> 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
#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.
>> 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 and rails/rails#36012 for the relevant changes.
If this blog was helpful, check out our full blog archive.