Class: URLCanonicalize::URI

Inherits:
Object
  • Object
show all
Defined in:
lib/url_canonicalize/uri.rb

Overview

Parses and normalizes URLs with local exception handling

Constant Summary collapse

VALID_CLASSES =
[::URI::HTTP, ::URI::HTTPS].freeze
SCHEME =

A scheme is recognized only as a leading scheme: token; a colon anywhere else no longer suppresses the default scheme

/\A[A-Za-z][A-Za-z0-9+.-]*:/

Class Method Summary collapse

Class Method Details

.normalize(url) ⇒ Object

Syntactic normalization per RFC 3986, via Addressable: lowercase scheme and host, internationalized hosts to punycode, uppercase percent-encodings with unreserved characters decoded, dot segments resolved, default ports removed and the empty path replaced by "/". Fragments are client-side state, so no canonical URL carries one



26
27
28
29
30
31
32
# File 'lib/url_canonicalize/uri.rb', line 26

def normalize(url)
  addressable = Addressable::URI.parse(decorate(url.to_s.strip)).normalize
  addressable.fragment = nil
  addressable.to_s
rescue Addressable::URI::InvalidURIError, ArgumentError, Encoding::CompatibilityError => e
  raise URLCanonicalize::Exception::URI, "#{e.class}: #{e.message}" # the original error becomes the cause
end

.parse(url) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/url_canonicalize/uri.rb', line 13

def parse(url)
  uri = ::URI.parse normalize(url)
  validate! uri
  uri
rescue ::URI::InvalidURIError => e
  raise URLCanonicalize::Exception::URI, "#{e.class}: #{e.message}" # the original error becomes the cause
end