If you look through the documentation for Pathname you won't find a Pathname#gsub
instance method. But there is a Pathname#sub.
So you get a (NoMethodError)
when you try to call it:
require 'pathname'
some_pathname = Pathname.new("path/with/two/path/occurances/")
p some_pathname.sub(/path/, 'foobar')
#=> #<Pathname:some/foobar/with/two/occurances/of/path>
p some_pathname.gsub(/path/, 'foobar')
# undefined method `gsub' (NoMethodError)
Why wouldn't Pathname
have a gsub
method? It seems like if you have a sub
you might as well have a gsub
.
Because ruby has open classes you can monkey patch the Pathname
class and add a gsub
instance method.
That's what I did below:
require 'pathname'
class Pathname
def gsub(re, str)
gsubbed_pn = self
while gsubbed_pn.to_s =~ re
gsubbed_pn = gsubbed_pn.sub(re, str)
end
gsubbed_pn
end
end
monkey_pathname = Pathname.new("path/with/two/path/occurances")
p monkey_pathname.gsub(/path/, 'foobar')
#=> #<Pathname:foobar/with/two/foobar/occurances>
p monkey_pathname
#<Pathname:path/with/two/path/occurances>
But I've read that monkey patching should probably not be the first tool I reach for.
Is there a better alternative in this case? Is Pathname
missing a gsub
method by design?