Skip to content

Instantly share code, notes, and snippets.

@NZKoz

NZKoz/3.1.diff Secret

Created June 7, 2011 23:12
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 NZKoz/89d6266cc7875614c5a5 to your computer and use it in GitHub Desktop.
Save NZKoz/89d6266cc7875614c5a5 to your computer and use it in GitHub Desktop.
From aedffb612ef2db67ec6ce064ce81fc36854515eb Mon Sep 17 00:00:00 2001
From: Michael Koziarski <michael@koziarski.com>
Date: Wed, 8 Jun 2011 09:31:03 +1200
Subject: [PATCH] Ensure that the strings returned by SafeBuffer#gsub and friends aren'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
---
.../core_ext/string/output_safety.rb | 13 +++++++++++++
activesupport/test/safe_buffer_test.rb | 12 ++++++++++++
2 files changed, 25 insertions(+), 0 deletions(-)
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
index c27cbc3..6df987e 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -74,6 +74,7 @@ end
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)
@@ -110,6 +111,18 @@ module ActiveSupport #:nodoc:
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
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index a4e2acb..3a98543 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -60,4 +60,16 @@ class SafeBufferTest < ActiveSupport::TestCase
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
--
1.7.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment