Skip to content

Instantly share code, notes, and snippets.

@h3h
Last active December 21, 2015 09:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save h3h/6287527 to your computer and use it in GitHub Desktop.
Save h3h/6287527 to your computer and use it in GitHub Desktop.
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