How do I safely join relative url segments?

前端 未结 11 1922
南方客
南方客 2020-12-30 19:27

I\'m trying to find a robust method of joining partial url path segments together. Is there a quick way to do this?

I tried the following:

puts URI::         


        
11条回答
  •  旧巷少年郎
    2020-12-30 20:19

    URI's api is not neccearily great.

    URI::join will work only if the first one starts out as an absolute uri with protocol, and the later ones are relative in the right ways... except I try to do that and can't even get that to work.

    This at least doesn't error, but why is it skipping the middle component?

     URI::join('http://somewhere.com/resource', './edit', '12?option=test') 
    

    I think maybe URI just kind of sucks. It lacks significant api on instances, such as an instance #join or method to evaluate relative to a base uri, that you'd expect. It's just kinda crappy.

    I think you're going to have to write it yourself. Or just use File.join and other File path methods, after testing all the edge cases you can think of to make sure it does what you want/expect.

    edit 9 Dec 2016 I figured out the addressable gem does it very nicely.

    base = Addressable::URI.parse("http://example.com")
    base + "foo.html"
    # => #
    
    base = Addressable::URI.parse("http://example.com/path/to/file.html")
    base + "relative_file.xml"
    # => #
    
    base = Addressable::URI.parse("https://example.com/path")
    base + "//newhost/somewhere.jpg"
    # => #
    
    base = Addressable::URI.parse("http://example.com/path/subpath/file.html")
    base + "../up-one-level.html"
    => #
    

提交回复
热议问题