Class: AcceptLanguage::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/accept_language/matcher.rb

Overview

Matches Accept-Language header values against application-supported languages to determine the optimal language choice. Handles quality values, wildcards, and language tag matching according to RFC 2616 specifications.

Examples:

Matcher.new("da" => 1.0, "en-GB" => 0.8, "en" => 0.7).call(:ug, :kk, :ru, :en) # => :en
Matcher.new("da" => 1.0, "en-GB" => 0.8, "en" => 0.7).call(:fr, :en, :"en-GB") # => :"en-GB"

Constant Summary collapse

WILDCARD =
"*"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**languages_range) ⇒ Matcher

Initialize a new Matcher object with the languages_range parameter representing the user’s preferred languages and their respective quality values.

Parameters:

  • languages_range (Hash<String, BigDecimal>)

    A hash where keys represent languages and values are the quality of preference for each language. A value of zero means the language is not acceptable.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/accept_language/matcher.rb', line 21

def initialize(**languages_range)
  @excluded_langtags = ::Set[]
  langtags = []

  languages_range.select do |langtag, quality|
    if quality.zero?
      @excluded_langtags << langtag unless wildcard?(langtag)
    else
      level = (quality * 1_000).to_i
      langtags[level] = langtag
    end
  end

  @preferred_langtags = langtags.compact.reverse
end

Instance Attribute Details

#excluded_langtagsObject (readonly)

Returns the value of attribute excluded_langtags.



14
15
16
# File 'lib/accept_language/matcher.rb', line 14

def excluded_langtags
  @excluded_langtags
end

#preferred_langtagsObject (readonly)

Returns the value of attribute preferred_langtags.



14
15
16
# File 'lib/accept_language/matcher.rb', line 14

def preferred_langtags
  @preferred_langtags
end

Instance Method Details

#call(*available_langtags) ⇒ String, ...

Finds the optimal language match by comparing user preferences against available languages. Handles priorities based on:

  1. Explicit quality values (q-values)

  2. Language tag specificity (exact matches preferred over partial matches)

  3. Order of preference in the original Accept-Language header

Parameters:

  • available_langtags (Array<String, Symbol>)

    Languages supported by your application

Returns:

  • (String, Symbol, nil)

    Best matching language or nil if no acceptable match found

Raises:

  • (ArgumentError)

    If any language tag is nil



46
47
48
49
50
51
52
53
# File 'lib/accept_language/matcher.rb', line 46

def call(*available_langtags)
  raise ::ArgumentError, "Language tags cannot be nil" if available_langtags.any?(&:nil?)

  filtered_tags = drop_unacceptable(*available_langtags)
  return nil if filtered_tags.empty?

  find_best_match(filtered_tags)
end