Skip to content

Instantly share code, notes, and snippets.

@h3h h3h/foo.rb

Last active Dec 21, 2015
Embed
What would you like to do?
Sanitizing HTML content in a Rails model.
class Foo < ActiveRecord::Base
ALLOWED_HTML_ELEMENTS = %w[
a b br blockquote code em h2 h3 hr i li ol p pre s strong sub sup u ul
]
ALLOWED_EMPTY_HTML_ELEMENTS = %w[br hr]
before_validation :sanitize_html
private
def sanitize_html
unwanted_nodes = Loofah::Scrubber.new do |node|
name = node.name.downcase
node.remove unless (ALLOWED_HTML_ELEMENTS + ['text']).include?(name)
node.remove if (node.blank? || node.content.blank?) && !ALLOWED_EMPTY_HTML_ELEMENTS.include?(name)
end
frag = Loofah.fragment(self.content).
scrub!(:nofollow).
scrub!(unwanted_nodes).
scrub!(unwanted_nodes) # two-pass for catching empty elements after removing bad elements
self.content = frag.to_html.squish.strip
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.