加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:04:56 所属栏目:百科 来源:网络整理
导读:我想使用端点和路径或主机和路径创建URL.不幸的是,URI.join不允许这样做: pry(main) URI.join "https://service.com","endpoint","/path"= #URI::HTTPS:0xa947f14 URL:https://service.com/pathpry(main) URI.join "https://service.com/endpoint","/path"=
我想使用端点和路径或主机和路径创建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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读