Permalink
Browse files

allow aliasing of gsub by providing generic version

  • Loading branch information...
timfel committed Sep 13, 2012
1 parent e31393e commit 7bb772ca761cbb54e5aeda7384ea7b9d260a4bb1
Showing with 36 additions and 0 deletions.
  1. +13 −0 src/kernel/bootstrap/String.rb
  2. +22 −0 src/test/github146.rb
  3. +1 −0 src/test/vmunit.conf
@@ -731,6 +731,15 @@ def _gsub_copyfrom_to(from, match_start)
self.__copyfrom_to( from + 1 , to )
end
+ # Generic version of gsub, for aliasing
+ def gsub(regex, str=nil, &block)
+ if str
+ _gsub_internal(regex, str)[0]
+ else
+ _gsub_internal_with_block(regex, &block)
+ end
+ end
+
# Returns a copy of <i>self</i> with <em>all</em> occurrences of <i>pattern</i>
# replaced with either <i>replacement</i> or the value of the block. The
# <i>pattern</i> will typically be a <code>Regexp</code>; if it is a
@@ -839,6 +848,10 @@ def __replace_match_with(match, replacement, flag=true)
def gsub(regex, &block)
+ _gsub_internal_with_block(regex, &block)
+ end
+
+ def _gsub_internal_with_block(regex, &block)
# if block_given?,
# $~ and related variables will be valid in block if
# blocks's home method and caller's home method are the same
View
@@ -0,0 +1,22 @@
+# https://github.com/MagLev/maglev/issues/143
+#
+# gsub has only specialized methods and thus cannot be aliased
+
+$gsub_runs = []
+
+class String
+ def gsub_with_logging(*arg, &block)
+ $gsub_runs << caller
+ gsub_without_logging(*arg, &block)
+ end
+ alias_method :gsub_without_logging, :gsub
+ alias_method :gsub, :gsub_with_logging
+end
+
+"hello".gsub("h", "b")
+raise unless $gsub_runs.size == 1
+
+"hello".gsub("h") { "b" }
+raise unless $gsub_runs.size == 2
+
+# Test passes if no exception is thrown
View
@@ -440,6 +440,7 @@ github106.rb
github126.rb
github140.rb
github143.rb
+github146.rb
testMarshal.rb # after other coverage of Hash
#

0 comments on commit 7bb772c

Please sign in to comment.