Let's say I'm outputting a post title and in our database, it's Hello Y’all
-- can I output it without using .html_safe
, but in such a way that it doesn't get output in html as Hello Y’all
?
That is, if a user copies a post title from a word processor that uses typographically correct apostrophes, I'm getting gibberish output since it's escaping the &
in the database as &
. Of course, I would want a title from the database that's Bonnie & Clyde
to be output as Bonnie & Clyde
since that is the correct HTML...
Is there a safe way to do this?
Use ActionView::Helpers::SanitizeHelper
<%= "Hello Y’all" %>
<%= sanitize "Hello Y’all" %>
will produce:
Hello Y’all
Hello Y’all
SafeBuffer calls ERB::Util.h
for strings that aren't html_safe
, so you can gsub
on ERB::Util.h(your_string)
and replace instances of &[code]
with &[code];
when first saving the string in your database. That way your string is first sanitized
The call you need is ERB::Util.h(your_string).gsub(/&(#x?[\da-fA-F]+;)/, '&\1')
Then whenever you need to display that particular string, call html_safe
on it.
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