gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:04:20 24 4
gpt4 key购买 nike

我想使用端点和路径或主机和路径创建 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/", "endpoint", "path"
=> "https://service.com/endpoint/path"
> join "http://example.com//////", "///////a/////////", "b", "c"
=> "http://example.com/a/b/c"

关于ruby-on-rails - 在 Rails 中使用主机和多个路径字符串创建 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com