diff --git a/html_terminator.gemspec b/html_terminator.gemspec
index 44cfc95..b362c5c 100644
--- a/html_terminator.gemspec
+++ b/html_terminator.gemspec
@@ -21,5 +21,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
- spec.add_runtime_dependency "sanitize"
+ spec.add_runtime_dependency "sanitize", "~> 4.0"
end
diff --git a/lib/html_terminator.rb b/lib/html_terminator.rb
index 340e1e8..d6073e6 100644
--- a/lib/html_terminator.rb
+++ b/lib/html_terminator.rb
@@ -7,13 +7,19 @@ module HtmlTerminator
}
def self.sanitize(val)
- if val and val.is_a?(String)
- Sanitize.clean(val, SANITIZE_OPTIONS).strip
+ if val.is_a?(String) && !skip_sanitize?(val)
+ Sanitize.fragment(val, SANITIZE_OPTIONS).strip.gsub(/&/, "&")
else
val
end
end
+ # Don't sanitize if only one bracket is present.
+ # Without this, "1 < 2" gets incorrectly sanitized as "1".
+ def self.skip_sanitize?(val)
+ val.count("<") + val.count(">") == 1
+ end
+
module ClassMethods
def terminate_html(*args)
class_attribute :html_terminator_fields
@@ -45,9 +51,9 @@ def terminate_html(*args)
# sanitize reads
self.html_terminator_fields.each do |attr|
- define_method "#{attr}" do |*args|
+ define_method(attr) do |*rargs|
# sanitize it
- HtmlTerminator.sanitize super(*args)
+ HtmlTerminator.sanitize super(*rargs)
end
end
end
@@ -73,4 +79,4 @@ def self.included(base)
end
end
-ActiveRecord::Base.send :include, HtmlTerminator
\ No newline at end of file
+ActiveRecord::Base.send :include, HtmlTerminator
diff --git a/spec/html_terminator_spec.rb b/spec/html_terminator_spec.rb
index e9a75a9..9db37a8 100644
--- a/spec/html_terminator_spec.rb
+++ b/spec/html_terminator_spec.rb
@@ -14,6 +14,30 @@
@user.age.should == 3
end
+ it "doesn't escape ampersands" do
+ @user = OnlyFirstName.new
+
+ @user.first_name = "A & B & C"
+ @user.first_name.should == "A & B & C"
+ end
+
+ it "skips sanitize when only one bracket" do
+ @user = OnlyFirstName.new
+
+ @user.first_name = "1 < 2"
+ @user.first_name.should == "1 < 2"
+
+ @user.first_name = "2 > 1"
+ @user.first_name.should == "2 > 1"
+ end
+
+ it "handles ampersands" do
+ @user = OnlyFirstName.new
+
+ @user.first_name = "Mr. & Mrs. Smith"
+ @user.first_name.should == "Mr. & Mrs. Smith"
+ end
+
it "sanitizes all except what is specified" do
@user = ExceptFirstName.new
@@ -35,4 +59,4 @@
@user.first_name = 1
@user.first_name.should == "1"
end
-end
\ No newline at end of file
+end