Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix for SafeBuffer#gsub and magic match globs

Only partial I'm afraid:
* $1, $2, $`, $&, and $’ now available within a block passed to gsub
* documented limitation that they are not available after the gsub call
* see GH#1555
  • Loading branch information...
commit 5107f3957666b9619dfad0177bcdca0db78db0f1 1 parent 1ae9b29
@tardate authored
View
16 activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -116,6 +116,22 @@ def #{unsafe_method}!(*args)
end
EOT
end
+
+ # Provides a special-case override for String#gsub
+ # to preserve some of the standard behaviour with respect
+ # to magic matching global variables
+ #
+ # Unlike standard gsub, magic matching globs are _not_
+ # available in code following a SafeBuffer#gsub call,
+ # but they are available within a block passed to gsub, eg:
+ # SafeBuffer.new('m').gsub(/(m)/){ $1 }
+ # In this case $1 == 'm' within the block, but not afterwards
+ #
+ # If you really need the magic matching variables after the gsub call
+ # you will need to covert SafeBuffer to a String first
+ def gsub(*args)
+ String.new(self).gsub(*args)
@Roman2K
Roman2K added a note

I think you forgot to forward the potential block here. Your test doesn't catch this since your assertion is placed within the block that isn't forwarded and thus never called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ end
end
end
View
18 activesupport/test/safe_buffer_test.rb
@@ -50,4 +50,22 @@ def setup
@buffer.gsub!('', 'asdf')
end
end
+
+ test "Should set magic match variables within block passed to gsub" do
+ 'clear'[/(matches)/]
+ @buffer << 'swan'
+ @buffer.gsub(/(swan)/) { assert_equal 'swan', $1 }
+ end
+
+ test "Should not expect magic match variables after gsub call" do
+ 'clear'[/(matches)/]
+ @buffer << 'vesta'
+ @buffer.gsub(/(vesta)/, '')
+ assert !$1, %(
+ if you can make this test fail it is a _good_ thing: somehow you have
+ restored the standard behaviour of SafeBuffer#gsub to make magic matching variables
+ available after the call, and you can probably deprecate this test
+ )
+ end
+
end
Please sign in to comment.
Something went wrong with that request. Please try again.