[前][次][番号順一覧][スレッド一覧]

ruby-changes:11367

From: akr <ko1@a...>
Date: Tue, 17 Mar 2009 14:26:30 +0900 (JST)
Subject: [ruby-changes:11367] Ruby:r22987 (trunk): * lib/pathname.rb (Pathname#sub): set $~ in block.binding.

akr	2009-03-17 14:26:15 +0900 (Tue, 17 Mar 2009)

  New Revision: 22987

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=22987

  Log:
    * lib/pathname.rb (Pathname#sub): set $~ in block.binding.
      [ruby-dev:38173]

  Modified files:
    trunk/ChangeLog
    trunk/lib/pathname.rb
    trunk/test/pathname/test_pathname.rb

Index: ChangeLog
===================================================================
--- ChangeLog	(revision 22986)
+++ ChangeLog	(revision 22987)
@@ -1,3 +1,8 @@
+Tue Mar 17 14:25:16 2009  Tanaka Akira  <akr@f...>
+
+	* lib/pathname.rb (Pathname#sub): set $~ in block.binding.
+	  [ruby-dev:38173]
+
 Tue Mar 17 13:48:08 2009  Nobuyoshi Nakada  <nobu@r...>
 
 	* win32/Makefile.sub (config.h): added RUBY_COREDLL.
Index: lib/pathname.rb
===================================================================
--- lib/pathname.rb	(revision 22986)
+++ lib/pathname.rb	(revision 22987)
@@ -254,7 +254,21 @@
 
   # 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
Index: test/pathname/test_pathname.rb
===================================================================
--- test/pathname/test_pathname.rb	(revision 22986)
+++ test/pathname/test_pathname.rb	(revision 22987)
@@ -471,6 +471,15 @@
   defassert(:pathsubext, 'fooaa.o', 'fooaa', '.o')
   defassert(:pathsubext, 'd.e/aa.o', 'd.e/aa', '.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

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]