使用Rails中的主机和多个路径字符串创建URL

mrz*_*asa 6 ruby uri ruby-on-rails

我想使用端点和路径或主机和路径创建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>
Run Code Online (Sandbox Code Playgroud)

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

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

URI.join("https://service.com", File.join("endpoint",  "/path"))
Run Code Online (Sandbox Code Playgroud)

你怎么看?

Dog*_*ert 7

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

你即将加入example.com,endpoint,/path,所以/path需要你回到域的根,而不是进行附加.

您需要使用a结束端点/,而不是使用开始路径/.

URI.join "https://service.com/", "endpoint/",  "path"
=> #<URI::HTTPS:0x007f8a5b0736d0 URL:https://service.com/endpoint/path>
Run Code Online (Sandbox Code Playgroud)

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

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

测试:

> join "https://service.com/", "endpoint", "path"
=> "https://service.com/endpoint/path"
> join "http://example.com//////", "///////a/////////", "b", "c"
=> "http://example.com/a/b/c"
Run Code Online (Sandbox Code Playgroud)

  • @the Tin Man:这与我是否在意无关——我知道我需要验证/规范化输入值。我只想提供一个看起来很方便的接口:传递端点和带或不带斜杠的路径。我认为有一个函数可以为我进行这种连接。如果没有 - 我会照顾。 (2认同)