Module: URLCanonicalize::LinkHeader

Extended by:
LinkHeader
Included in:
LinkHeader
Defined in:
lib/url_canonicalize/link_header.rb

Overview

Parses HTTP Link header fields (RFC 8288) far enough to find the target of the first link whose rel tokens include "canonical"

Constant Summary collapse

/<([^>]*)>((?:\s*;\s*[\w!#$%&'*+.^`|~-]+\s*=\s*(?:"[^"]*"|[^",;]+))*)/
REL_PARAM =
/;\s*rel\s*=\s*(?:"([^"]*)"|([^",;\s]+))/i
CANONICAL =
'canonical'

Instance Method Summary collapse

Instance Method Details

#canonical(response) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/url_canonicalize/link_header.rb', line 13

def canonical(response)
  fields = response.get_fields('link')
  return unless fields

  fields.each do |field|
    field.scan(LINK_VALUE) do |target, params|
      return target if canonical?(params)
    end
  end

  nil
end

#canonical?(params) ⇒ Boolean

Returns:

  • (Boolean)


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

def canonical?(params)
  match = REL_PARAM.match(params)
  return false unless match

  rel = match[1] || match[2]
  rel.split.any? { |token| token.casecmp?(CANONICAL) }
end