Module: Philiprehberger::HeaderKit::Negotiation

Defined in:
lib/philiprehberger/header_kit/negotiation.rb

Overview

Content negotiation logic for matching Accept headers against available media types.

Class Method Summary collapse

Class Method Details

.negotiate(accept_header, available) ⇒ String?

Find the best matching media type from available types based on an Accept header.

Matching rules (RFC 7231):

  1. Exact type match

  2. Subtype wildcard (e.g., text/* matches text/html)

  3. Full wildcard (/) matches anything

Parameters:

  • accept_header (String)

    the Accept header value

  • available (Array<String>)

    list of available media types

Returns:

  • (String, nil)

    the best matching type, or nil if no match



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/philiprehberger/header_kit/negotiation.rb', line 17

def self.negotiate(accept_header, available)
  return nil if available.nil? || available.empty?
  return available.first if accept_header.nil? || accept_header.strip.empty?

  accepted = Accept.parse(accept_header)
  return nil if accepted.empty?

  best_match = nil
  best_quality = -1.0
  best_specificity = -1

  accepted.each do |entry|
    available.each do |candidate|
      specificity = match_specificity(entry[:type], candidate)
      next unless specificity >= 0
      next unless entry[:quality] > best_quality ||
                  (entry[:quality] == best_quality && specificity > best_specificity)

      best_match = candidate
      best_quality = entry[:quality]
      best_specificity = specificity
    end
  end

  best_quality > 0.0 ? best_match : nil
end