diff --git a/lib/pathname.rb b/lib/pathname.rb index 9a29752..d8fe335 100644 --- a/lib/pathname.rb +++ b/lib/pathname.rb @@ -544,6 +544,19 @@ def relative_path_from(base_directory) Pathname.new(File.join(*relpath_names)) end end + + # Return a pathname whose basename is substituted by String#sub. + # + # path1 = Pathname.new('/usr/bin/perl') + # path1.basename_sub('perl', 'ruby') + # #=> # + # path1.basename_sub(/\Aperl\z/, 'ruby') + # #=> # + # + def basename_sub(pattern, replacement) + dir, base = split + dir + base.sub(pattern, replacement) + end end @@ -597,4 +610,3 @@ def rmtree(noop: nil, verbose: nil, secure: nil) nil end end - diff --git a/test/pathname/test_pathname.rb b/test/pathname/test_pathname.rb index a23dc21..c110a17 100644 --- a/test/pathname/test_pathname.rb +++ b/test/pathname/test_pathname.rb @@ -557,6 +557,15 @@ def test_comparison_string def pathsub(path, pat, repl) Pathname.new(path).sub(pat, repl).to_s end defassert(:pathsub, "a.o", "a.c", /\.c\z/, ".o") + defassert(:pathsub, "bar/bar", "bar/foo", "foo", "bar") + + def pathbasesub(path, pat, repl) Pathname.new(path).basename_sub(pat, repl).to_s end + defassert(:pathbasesub, "a.o", "a.c", /\.c\z/, ".o") + defassert(:pathbasesub, "bar", "foo", "foo", "bar") + defassert(:pathbasesub, "bar", "foo", /\Afoo\z/, "bar") + defassert(:pathbasesub, "foo/bar", "foo/foo", "foo", "bar") + defassert(:pathbasesub, "foo/bar", "foo/foo", /\Afoo\z/, "bar") + defassert(:pathbasesub, "foo/fofo", "foo/foo", /\A(fo)o\z/, '\1\1') def pathsubext(path, repl) Pathname.new(path).sub_ext(repl).to_s end defassert(:pathsubext, 'a.o', 'a.c', '.o')