我想使用端点和路径或主机和路径创建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"