开发者

How do I inherit from Pathname in Ruby?

开发者 https://www.devze.com 2023-04-05 05:52 出处:网络
I have a RemoteFile that inherits from Pathname class RemoteFile < Pathname end I create a remote file, and get its parent

I have a RemoteFile that inherits from Pathname

class RemoteFile < Pathname
end

I create a remote file, and get its parent

    irb> RemoteFile.new('.')
     => #<RemoteFile:.> 
    irb> RemoteFile.new('.').parent
     => #<Pathname:..>

Is there any way to get Pathname to return RemoteFiles besides monkey-patching a dozen methods in Pat开发者_C百科hname? Wouldn't it work better if Pathname returned objects of type self.class.new?


This worked for me so far:

class Winpath < Pathname
   def to_s
      super.tr("/", "\\")
   end

   def +(other)
      self.class.new super(other)
   end
end

Seems like +(other) is the only function you need to overload.


You could consider delegating to an actual Pathname object. Have a look at this article. This way you wouldn't have to monkey patch anything, and because of delegation, you could modify things in a safer, more controllable way.


In fact you can just reopen the Pathname class instead of inheriting it.

0

精彩评论

暂无评论...
验证码 换一张
取 消