From d6c77c9647af5086323bcad325803114431d5901 Mon Sep 17 00:00:00 2001 From: akr Date: Tue, 17 Mar 2009 05:56:59 +0000 Subject: [PATCH] * lib/pathname.rb (Pathname#sub): set $~ in block.binding. [ruby-dev:38173] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@22988 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ lib/pathname.rb | 16 +++++++++++++++- test/pathname/test_pathname.rb | 9 +++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 379002b293..e18326a370 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Tue Mar 17 14:56:26 2009 Tanaka Akira + + * lib/pathname.rb (Pathname#sub): set $~ in block.binding. + [ruby-dev:38173] + Mon Mar 16 16:37:22 2009 Nobuyoshi Nakada * ext/tk/tcltklib.c (eventloop_sleep, lib_eventloop_core), diff --git a/lib/pathname.rb b/lib/pathname.rb index 1f1433634a..5c723a7c20 100644 --- a/lib/pathname.rb +++ b/lib/pathname.rb @@ -251,7 +251,21 @@ class Pathname # Return a pathname which is substituted by String#sub. def sub(pattern, *rest, &block) - self.class.new(@path.sub(pattern, *rest, &block)) + if block + path = @path.sub(pattern, *rest) {|*args| + begin + old = Thread.current[:pathname_sub_matchdata] + Thread.current[:pathname_sub_matchdata] = $~ + eval("$~ = Thread.current[:pathname_sub_matchdata]", block.binding) + ensure + Thread.current[:pathname_sub_matchdata] = old + end + yield *args + } + else + path = @path.sub(pattern, *rest) + end + self.class.new(path) end if File::ALT_SEPARATOR diff --git a/test/pathname/test_pathname.rb b/test/pathname/test_pathname.rb index 9b0b9c01e8..f94c123dec 100644 --- a/test/pathname/test_pathname.rb +++ b/test/pathname/test_pathname.rb @@ -381,6 +381,15 @@ class TestPathname < Test::Unit::TestCase def pathsub(path, pat, repl) Pathname.new(path).sub(pat, repl).to_s end defassert(:pathsub, "a.o", "a.c", /\.c\z/, ".o") + def test_sub_matchdata + result = Pathname("abc.gif").sub(/\..*/) { + assert_not_nil($~) + assert_equal(".gif", $~[0]) + ".png" + } + assert_equal("abc.png", result.to_s) + end + def root?(path) Pathname.new(path).root? end