Permalink
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...
tardate committed Jun 10, 2011
1 parent 1ae9b29 commit 5107f3957666b9619dfad0177bcdca0db78db0f1
@@ -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)

This comment has been minimized.

Show comment Hide comment
@Roman2K

Roman2K Jun 12, 2011

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.

@Roman2K

Roman2K Jun 12, 2011

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.

+ end
end
end
@@ -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

0 comments on commit 5107f39

Please sign in to comment.