ruby-on-rails – 使用Rails中的主机和多个路径字符串创建URL

我想使用端点和路径或主机和路径创建URL.不幸的是,URI.join不允许这样做:
pry(main)> URI.join "https://service.com","endpoint","/path"
=> #<URI::HTTPS:0xa947f14 URL:https://service.com/path>
pry(main)> URI.join "https://service.com/endpoint","/path"
=> #<URI::HTTPS:0xabba56c URL:https://service.com/path>

我想要的是:“https://service.com/endpoint/path”.我怎么能在Ruby / Rails中做到这一点?

编辑:由于URI.join有一些缺点,我很想使用File.join:

URI.join("https://service.com",File.join("endpoint","/path"))

你怎么看?

解决方法

URI.join就像你期望的那样< a>标签工作.

您正在加入example.com,endpoint,/ path,因此/ path会将您带回域的根目录,而不是附加它.

您需要使用/结束端点,而不是使用/启动路径.

URI.join "https://service.com/","endpoint/","path"
=> #<URI::HTTPS:0x007f8a5b0736d0 URL:https://service.com/endpoint/path>

编辑:根据您在下面评论中的请求,试试这个:

def join(*args)
  args.map { |arg| arg.gsub(%r{^/*(.*?)/*$},'\1') }.join("/")
end

测试:

> join "https://service.com/","path"
=> "https://service.com/endpoint/path"
> join "http://example.com//////","///////a/////////","b","c"
=> "http://example.com/a/b/c"

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...