让 ruby Pathname#join 表现得像 File.join 并且不会破坏接收者路径的简单方法?
根据 rubydoc,如果传递给 Pathname#join (或 Pathname#+)的参数是绝对的,则方法接收者的路径将被完全忽略。示例:
Pathname('/home/foo').join '/etc/passwd'
# => #<Pathname:/etc/passwd>
但是
File.join('/home/foo', '/etc/passwd')
# => "/home/foo/etc/passwd"
Pathname 通常使用起来很愉快,但它的连接行为确实很烦人,我想不出什么时候我会希望这种情况发生。
是否存在类似于 File.join 的现有方法?它应该对路径名和字符串进行操作。
像这样的冗长解决方案是不可接受的:
Pathname( File.join(pn, '/etc/passwd') )
我可以接受猴子补丁,但它们必须比这更好:
class Pathname
def safe_join(other)
Pathname.new(File.join(self, other))
end
end
According to the rubydoc, if the argument passed to Pathname#join (or Pathname#+) is absolute, the method receiver's path is completely ignored. Example:
Pathname('/home/foo').join '/etc/passwd'
# => #<Pathname:/etc/passwd>
but
File.join('/home/foo', '/etc/passwd')
# => "/home/foo/etc/passwd"
Pathname is usually a pleasure to use, but its join behavior is a real annoyance, and I can't think of when I'd ever want that to happen.
Is there an existing method that acts like File.join? It should operate on a Pathname and a string.
A verbose solution like this is not acceptable:
Pathname( File.join(pn, '/etc/passwd') )
I may accept monkey patches, but they have to be better than this:
class Pathname
def safe_join(other)
Pathname.new(File.join(self, other))
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
File.expand_path
的行为与此相同,我认为这是正确的行为。File.join
以不同的方式操作,仅用于使用适当的分隔符连接路径的元素,其中/
、\
甚至:
的使用取决于操作系统。File.expand_path
在另一个路径规范的上下文中解释路径规范,并允许以与绝对路径不同的方式处理相对路径。这是一个重要的区别,特别是对于配置文件。如果您要创建自己的方法,则可能需要为其指定一个不同的名称,例如
hard_join
或concat
。File.expand_path
behaves the same way as this, and I'd argue it's the proper behavior.File.join
operates in a different way and merely serves to join the elements of the path with the proper separator, where/
,\
or even:
are used depending on the OS.File.expand_path
interprets a path specification in the context of another, and allows for relative paths to be handled differently from absolute paths. This is an important distinction, especially for configuration files.If you're going to make your own method, you might want to give it a different name, like
hard_join
orconcat
.如何使用正则表达式去除任何前面的
/
:How about using a regex to strip off any preceding
/
: