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?
SafeBuffer calls
ERB::Util.hfor strings that aren’thtml_safe, so you cangsubonERB::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 sanitizedThe 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_safeon it.