Strip html from string Ruby on Rails
To strip HTML tags from a string in Ruby on Rails, use the strip_tags
method:
Remember to add ActionView::Helpers::SanitizeHelper if you are venturing outside the kingdom of views or helpers.
Preserving value attribute's text
The strip_tags
function takes care of the children, really. It helps you retain the text content even within attributes like value
. Here's the trick:
Thanks to ActionView::Base.full_sanitizer.sanitize, even the daunting specter of XSS attacks is kept at bay.
Handling complex HTML with Nokogiri
For a HTML structure that looks like spaghetti code, Nokogiri can be your Swiss knife. Control it with Xpath like a pro:
Simply put, Nokogiri makes advanced manipulation of HTML/XML look like child's play.
Loofah: Your sanitization companion
Meet Loofah, a gem that wears many hats:
Loofah is all about extensive sanitization and aligns well with Rails' "safety first" mantra.
Customizing HTML tag allowance
What if you want to play favorites with HTML tags and attributes? sanitize
with :tags
and :attributes
is your answer, and %w()
your secret handshake:
Scenario-based solutions
Let's move further into our journey of scenarios and their respective solutions:
Retaining simple formatting: An art form
How to keep basic text formatting while warding off XSS threats?
Custom sanitization: Not as hard as it sounds
Building a tailor-made cure with Loofah:
Keeping links safe: Mission Possible!
Make links secure with rails-html-sanitizer
and keep your cyber world safe:
Was this article helpful?