Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/pathname.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
# #=> #<Pathname:/usr/bin/ruby>
# path1.basename_sub(/\Aperl\z/, 'ruby')
# #=> #<Pathname:/usr/bin/ruby>
#
def basename_sub(pattern, replacement)
dir, base = split
dir + base.sub(pattern, replacement)
end
end


Expand Down Expand Up @@ -597,4 +610,3 @@ def rmtree(noop: nil, verbose: nil, secure: nil)
nil
end
end

9 changes: 9 additions & 0 deletions test/pathname/test_pathname.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down