How do I safely join relative url segments?

前端 未结 11 1946
南方客
南方客 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:13

    Use this code:

    File.join('resource/', '/edit', '12?option=test').
         gsub(File::SEPARATOR, '/').
         sub(/^\//, '')
    # => resource/edit/12?option=test
    

    example with empty strings:

    File.join('', '/edit', '12?option=test').
         gsub(File::SEPARATOR, '/').
         sub(/^\//, '')
    # => edit/12?option=test
    

    Or use this if possible to use segments like resource/, edit/, 12?option=test and where http: is only a placeholder to get a valid URI. This works for me.

    URI.
      join('http:', 'resource/', 'edit/', '12?option=test').
      path.
      sub(/^\//, '')
    # => "resource/edit/12"
    

提交回复
热议问题