Skip to content

Commit

Permalink
Ensure that the strings returned by SafeBuffer#gsub and friends aren'…
Browse files Browse the repository at this point in the history
…t considered html_safe?

Also make sure that the versions of those methods which modify a string in place such as gsub! can't be called on safe buffers at all.

Conflicts:

	activesupport/test/safe_buffer_test.rb
  • Loading branch information
NZKoz authored and tenderlove committed Jun 7, 2011
1 parent b7ea35d commit 6766caf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions activesupport/lib/active_support/core_ext/string/output_safety.rb
Expand Up @@ -74,6 +74,7 @@ def html_safe?

module ActiveSupport #:nodoc:
class SafeBuffer < String
UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"].freeze
alias safe_concat concat

def concat(value)
Expand Down Expand Up @@ -110,6 +111,18 @@ def to_yaml(*args)

to_str.to_yaml(*args)
end

for unsafe_method in UNSAFE_STRING_METHODS
class_eval <<-EOT, __FILE__, __LINE__
def #{unsafe_method}(*args)
super.to_str
end
def #{unsafe_method}!(*args)
raise TypeError, "Cannot modify SafeBuffer in place"
end
EOT
end
end
end

Expand Down
12 changes: 12 additions & 0 deletions activesupport/test/safe_buffer_test.rb
Expand Up @@ -60,4 +60,16 @@ def test_nested
yaml = YAML.dump data
assert_equal({'str' => str}, YAML.load(yaml))
end

test "Should not return safe buffer from gsub" do
altered_buffer = @buffer.gsub('', 'asdf')
assert_equal 'asdf', altered_buffer
assert !altered_buffer.html_safe?
end

test "Should not allow gsub! on safe buffers" do
assert_raise TypeError do
@buffer.gsub!('', 'asdf')
end
end
end

0 comments on commit 6766caf

Please sign in to comment.