Skip to content

Instantly share code, notes, and snippets.

@darkhelmet
Forked from vigetlabs/statham_sanitizer.rb
Created November 23, 2009 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkhelmet/241183 to your computer and use it in GitHub Desktop.
Save darkhelmet/241183 to your computer and use it in GitHub Desktop.
module HTML
class StathamSanitizer < WhiteListSanitizer
protected
def tokenize(text, options)
super.map do |token|
if token.is_a?(HTML::Tag) && options[:parent].include?(token.name)
token.to_s.gsub(/</, "&lt;")
else
token
end
end
end
def process_node(node, result, options)
result << case node
when HTML::Tag
if node.closing == :close && options[:parent].first == node.name
options[:parent].shift
elsif node.closing != :self
options[:parent].unshift node.name
end
process_attributes_for node, options
if options[:tags].include?(node.name)
node
else
bad_tags.include?(node.name) ? nil : node.to_s.gsub(/</, "&lt;")
end
else
bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;")
end
end
end
end
require File.dirname(__FILE__) + '/../test_helper'
class StathamSanitizerTest < ActiveSupport::TestCase
context "A StathamSanitizer" do
setup do
@sanitizer = HTML::StathamSanitizer.new
end
should "escape tags that are neither allowed nor banned" do
assert_equal "&lt;font>Hello&lt;/font>", @sanitizer.sanitize("<font>Hello</font>")
end
should "escape tags that are allowed but unclosed" do
assert_equal "&lt;p>Hello", @sanitizer.sanitize("<p>Hello")
end
should "escape tags that are closed without ever being opened" do
assert_equal "Hello&lt;/p>", @sanitizer.sanitize("Hello</p>")
end
should "include tags that are allowed and self-closing" do
assert_equal "Hello<br />", @sanitizer.sanitize("Hello<br />")
end
should "escape comments" do
assert_equal "&lt;!-- comment", @sanitizer.sanitize("<!-- comment")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment