summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenoit Daloze <eregontp@gmail.com>2025-11-04 15:00:18 +0100
committerHiroshi SHIBATA <hsbt@ruby-lang.org>2025-11-05 14:52:58 +0900
commitf8d1291162d45db18f51f0a8e0e27bb1f98b60ae (patch)
tree87ff609748e0cce718a4383b99c3f79bd92613e2
parentf8e9bccd03f3e62e2f25cc08d5d5c6861347a0fe (diff)
Support passing a #to_str object to Pathname.new for compatibility
* See https://github.com/ruby/pathname/pull/57#issuecomment-3485646510
-rw-r--r--pathname_builtin.rb3
-rw-r--r--test/pathname/test_pathname.rb4
2 files changed, 6 insertions, 1 deletions
diff --git a/pathname_builtin.rb b/pathname_builtin.rb
index 16ed219ec3..1dedf5e08d 100644
--- a/pathname_builtin.rb
+++ b/pathname_builtin.rb
@@ -217,7 +217,8 @@ class Pathname
def initialize(path)
unless String === path
path = path.to_path if path.respond_to? :to_path
- raise TypeError unless String === path
+ path = path.to_str if path.respond_to? :to_str
+ raise TypeError, "Pathname.new requires a String, #to_path or #to_str" unless String === path
end
if path.include?("\0")
diff --git a/test/pathname/test_pathname.rb b/test/pathname/test_pathname.rb
index e80473e5a3..e2d6a09fb2 100644
--- a/test/pathname/test_pathname.rb
+++ b/test/pathname/test_pathname.rb
@@ -484,6 +484,10 @@ class TestPathname < Test::Unit::TestCase
assert_equal('a', p1.to_s)
p2 = Pathname.new(p1)
assert_equal(p1, p2)
+
+ obj = Object.new
+ def obj.to_str; "a/b"; end
+ assert_equal("a/b", Pathname.new(obj).to_s)
end
def test_initialize_nul