Class: AcceptLanguage::Matcher

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

Overview

Note:

Compare an Accept-Language header value with your application's supported languages to find the common languages that could be presented to a user.

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

Returns a new instance of Matcher.

Parameters:

  • languages_range (Hash<String, BigDecimal>)

    A list of accepted languages with their respective qualities.


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/accept_language/matcher.rb', line 17

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.


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

def excluded_langtags
  @excluded_langtags
end

#preferred_langtagsObject (readonly)

Returns the value of attribute preferred_langtags.


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

def preferred_langtags
  @preferred_langtags
end

Instance Method Details

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

Returns The language that best matches.

Examples:

Uyghur, Kazakh, Russian and English languages are available.

call(:ug, :kk, :ru, :en)

Parameters:

  • available_langtags (Array<String, Symbol>)

    The list of available languages.

Returns:

  • (String, Symbol, nil)

    The language that best matches.


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/accept_language/matcher.rb', line 38

def call(*available_langtags)
  available_langtags = drop_unacceptable(*available_langtags)

  preferred_langtags.each do |preferred_tag|
    if wildcard?(preferred_tag)
      langtag = any_other_langtag(*available_langtags)
      return langtag unless langtag.nil?
    else
      available_langtags.each do |available_langtag|
        return available_langtag if available_langtag.match?(/\A#{preferred_tag}/i)
      end
    end
  end

  nil
end