Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Being html_safe in Rails while retaining html entities?

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?

like image 215
Aaron Gibralter Avatar asked Sep 05 '25 03:09

Aaron Gibralter


2 Answers

Use ActionView::Helpers::SanitizeHelper

<%= "Hello Y&#8217;all" %>
<%= sanitize "Hello Y&#8217;all" %>

will produce:

Hello Y&#8217;all
Hello Y’all
like image 130
Maciej Majewski Avatar answered Sep 07 '25 19:09

Maciej Majewski


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 &amp;[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(/&amp;(#x?[\da-fA-F]+;)/, '&\1')

Then whenever you need to display that particular string, call html_safe on it.

like image 30
magni- Avatar answered Sep 07 '25 21:09

magni-