Skip to content

Instantly share code, notes, and snippets.

@freiden
Forked from h3h/foo.rb
Created August 21, 2013 09:08
Show Gist options
  • Save freiden/6292092 to your computer and use it in GitHub Desktop.
Save freiden/6292092 to your computer and use it in GitHub Desktop.
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