如何从Ruby中的Pathname继承?

时间:2022-09-24 23:33:27

I have a RemoteFile that inherits from Pathname

我有一个继承自Pathname的RemoteFile

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 Pathname? Wouldn't it work better if Pathname returned objects of type self.class.new?

除了在路径名中修补十几个方法之外,有没有办法让Pathname返回RemoteFiles?如果Pathname返回self.class.new类型的对象,它会不会更好?

3 个解决方案

#1


1  

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.

您可以考虑委托给实际的Pathname对象。看看这篇文章。这样你就不必修补任何东西,并且由于委托,你可以用更安全,更可控的方式修改东西。

#2


2  

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.

似乎+(other)是你需要重载的唯一功能。

#3


0  

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

实际上,您可以重新打开Pathname类而不是继承它。

#1


1  

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.

您可以考虑委托给实际的Pathname对象。看看这篇文章。这样你就不必修补任何东西,并且由于委托,你可以用更安全,更可控的方式修改东西。

#2


2  

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.

似乎+(other)是你需要重载的唯一功能。

#3


0  

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

实际上,您可以重新打开Pathname类而不是继承它。