Skip to content

Commit

Permalink
Merge pull request #1 from polleverywhere/skip_one_bracket_sanitize
Browse files Browse the repository at this point in the history
Skip sanitize when only one bracket is present
  • Loading branch information
steel committed Aug 3, 2015
2 parents 7cb1fa7 + 1511749 commit 6b6de31
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 7 deletions.
2 changes: 1 addition & 1 deletion html_terminator.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -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
16 changes: 11 additions & 5 deletions lib/html_terminator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -73,4 +79,4 @@ def self.included(base)
end
end

ActiveRecord::Base.send :include, HtmlTerminator
ActiveRecord::Base.send :include, HtmlTerminator
26 changes: 25 additions & 1 deletion spec/html_terminator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -35,4 +59,4 @@
@user.first_name = 1
@user.first_name.should == "1"
end
end
end

0 comments on commit 6b6de31

Please sign in to comment.