Create url using host and multiple path lines in Rails

I would like to create a URL using the endpoint and path or the host and path. Unfortunately, this URI.joindoes not allow to do this:

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>

and I want to: "https://service.com/endpoint/path". How can I do this in Ruby / Rails?

The EDIT: . Since it URI.joinhas some disadvantage, I am tempted to use File.join:

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

What do you think?

+5
source share
3 answers

URI.join works the way you expected the tag <a>to work.

You join example.com, endpoint, /path, so /pathreturns you back to the root domain instead of adding.

/, /.

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"
+6

, URI.join '/', URL-. , '/' , . :

URI.join("https://service.com", 'omitted_part', 'omitted_again', 'end_point_stays').to_s
# =>"https://service.com/end_point_stays"

, , , , - uri , - .

, , , :

URI.join("https://service.com", 'omitted_no_trailing_slash', 'omitted_again', 'stays/', 'end_point_stays').to_s
# => "https://service.com/stays/end_point_stays"

, , , , :

URI.join("https://service.com/omitted_because_no_trailing_slash", 'end_point_stays').to_s
# => "https://service.com/end_point_stays"
URI.join("https://service.com/stays_because_of_trailing_slash/", 'end_point_stays').to_s
# => "https://service.com/stays_because_of_trailing_slash/end_point_stays"
URI.join("https://service.com/safe_with_trailing_slash/omitted_because_no_trailing_slash", 'end_point_stays').to_s
# => "https://service.com/safe_with_trailing_slash/end_point_stays"
+3

I made a script so you can do something like:

SmartURI.join('http://example.com/subpath', 'hello', query: { token: secret })
=> "http://example.com/subpath/hello?token=secret"

https://gist.github.com/zernel/0f10c71f5a9e044653c1a65c6c5ad697

0
source

All Articles