Method: Addressable::URI#route_from

Defined in:
lib/addressable/uri.rb

#route_from(uri) ⇒ Addressable::URI

Returns the shortest normalized relative form of this URI that uses the supplied URI as a base for resolution. Returns an absolute URI if necessary. This is effectively the opposite of route_to.

Parameters:

Returns:

  • (Addressable::URI)

    The normalized relative URI that is equivalent to the original URI.



2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
# File 'lib/addressable/uri.rb', line 2085

def route_from(uri)
  uri = URI.parse(uri).normalize
  normalized_self = self.normalize
  if normalized_self.relative?
    raise ArgumentError, "Expected absolute URI, got: #{self.to_s}"
  end
  if uri.relative?
    raise ArgumentError, "Expected absolute URI, got: #{uri.to_s}"
  end
  if normalized_self == uri
    return Addressable::URI.parse("##{normalized_self.fragment}")
  end
  components = normalized_self.to_hash
  if normalized_self.scheme == uri.scheme
    components[:scheme] = nil
    if normalized_self.authority == uri.authority
      components[:user] = nil
      components[:password] = nil
      components[:host] = nil
      components[:port] = nil
      if normalized_self.path == uri.path
        components[:path] = nil
        if normalized_self.query == uri.query
          components[:query] = nil
        end
      else
        if uri.path != SLASH and components[:path]
          self_splitted_path = split_path(components[:path])
          uri_splitted_path = split_path(uri.path)
          self_dir = self_splitted_path.shift
          uri_dir = uri_splitted_path.shift
          while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
            self_dir = self_splitted_path.shift
            uri_dir = uri_splitted_path.shift
          end
          components[:path] = (uri_splitted_path.fill('..') + [self_dir] + self_splitted_path).join(SLASH)
        end
      end
    end
  end
  # Avoid network-path references.
  if components[:host] != nil
    components[:scheme] = normalized_self.scheme
  end
  return Addressable::URI.new(
    :scheme => components[:scheme],
    :user => components[:user],
    :password => components[:password],
    :host => components[:host],
    :port => components[:port],
    :path => components[:path],
    :query => components[:query],
    :fragment => components[:fragment]
  )
end