In Ruby on Rails, given a string, is it possible to determine whether .html_safe has been called on that string?
Reason for asking: I'd like to write a controller unit test that verifies that html_safe has not been called on a particular string, in order to prove that when that string later gets rendered onto a page in a view, Rails will escape the string (avoiding possible XSS vulnerabilities).
I realize that I could instead go ahead and actually render the page in my test, and then inspect the rendered page body, but I'm wondering if there's a more direct way of doing this?
There's html_safe?
:
s = 'foo'
s.html_safe? #=> false
s = 'foo'.html_safe
s.html_safe? #=> true
Note that an ActiveSupport::SafeBuffer
reverts to unsafe if you call a "destructive" method:
s = 'foo'.html_safe
s.html_safe? #=> true
s.capitalize! #=> 'Foo'
s.html_safe? #=> false
.html_safe
actually returns not an object of type String, but an object of type ActiveSupport::SafeBuffer (which is a derived class of String).
Therefore, calling:
my_string.is_a?(ActiveSupport::SafeBuffer)
will return false
only when the string is not the result of a call to .html_string
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With