From 524724ec558c9fc1d9fbfbdba0d16c0620cdfa67 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 4 Nov 2025 15:00:18 +0100 Subject: [PATCH] Support passing a #to_str object to Pathname.new for compatibility * See https://github.com/ruby/pathname/pull/57#issuecomment-3485646510 --- lib/pathname.rb | 3 ++- test/pathname/test_pathname.rb | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/pathname.rb b/lib/pathname.rb index a0db812..a7bd304 100644 --- a/lib/pathname.rb +++ b/lib/pathname.rb @@ -237,7 +237,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 e80473e..e2d6a09 100644 --- a/test/pathname/test_pathname.rb +++ b/test/pathname/test_pathname.rb @@ -484,6 +484,10 @@ def test_initialize 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