Module: Dommy::Rails::UrlNormalizer
- Defined in:
- lib/dommy/rails/url_normalizer.rb
Overview
Normalizes URLs so Rails URL-helper output and rendered HTML compare equal despite representational differences.
Deliberately lenient: scheme and host are dropped, query parameters are sorted, HTML entities are unescaped, and trailing slashes are removed. Strict external-host matching is out of scope (see README).
Class Method Summary collapse
Class Method Details
.equal?(expected, actual) ⇒ Boolean
18 19 20 |
# File 'lib/dommy/rails/url_normalizer.rb', line 18 def equal?(expected, actual) normalize(expected) == normalize(actual) end |
.normalize(url) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/dommy/rails/url_normalizer.rb', line 22 def normalize(url) url = url.to_s return "" if url.empty? # Attribute values may arrive HTML-escaped (e.g. & in raw # response bodies). url = CGI.unescapeHTML(url) uri = URI.parse(url) path = uri.path.to_s path = path.chomp("/") unless path == "/" query = if uri.query params = URI.decode_www_form(uri.query).sort_by { |k, _| k } URI.encode_www_form(params) end [path, query].compact.join("?") rescue URI::InvalidURIError url end |