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"

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.



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

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

  languages_range.select do |langtag, quality|
    if quality.zero?
      @excluded_langtags << langtag unless langtag.eql?("*")
    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.



11
12
13
# File 'lib/accept_language/matcher.rb', line 11

def excluded_langtags
  @excluded_langtags
end

#preferred_langtagsObject (readonly)

Returns the value of attribute preferred_langtags.



11
12
13
# File 'lib/accept_language/matcher.rb', line 11

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.



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

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

  preferred_langtags.each do |preferred_tag|
    if preferred_tag.eql?("*")
      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