-
-
Save freiden/6292092 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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