Class: AcceptLanguage::Matcher
- Inherits:
-
Object
- Object
- AcceptLanguage::Matcher
- Defined in:
- lib/accept_language/matcher.rb
Overview
A utility class that provides functionality to match the Accept-Language header value against the languages supported by your application. This helps in identifying the most suitable languages to present to the user based on their preferences.
Constant Summary collapse
- WILDCARD =
"*"
Instance Attribute Summary collapse
-
#excluded_langtags ⇒ Object
readonly
Returns the value of attribute excluded_langtags.
-
#preferred_langtags ⇒ Object
readonly
Returns the value of attribute preferred_langtags.
Instance Method Summary collapse
-
#call(*available_langtags) ⇒ String, ...
Matches the user’s preferred languages against the available languages of your application.
-
#initialize(**languages_range) ⇒ Matcher
constructor
Initialize a new Matcher object with the languages_range parameter representing the user’s preferred languages and their respective quality values.
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.
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[] = [] languages_range.select do |langtag, quality| if quality.zero? @excluded_langtags << langtag unless wildcard?(langtag) else level = (quality * 1_000).to_i [level] = langtag end end @preferred_langtags = .compact.reverse end |
Instance Attribute Details
#excluded_langtags ⇒ Object (readonly)
Returns the value of attribute excluded_langtags.
14 15 16 |
# File 'lib/accept_language/matcher.rb', line 14 def @excluded_langtags end |
#preferred_langtags ⇒ Object (readonly)
Returns the value of attribute preferred_langtags.
14 15 16 |
# File 'lib/accept_language/matcher.rb', line 14 def @preferred_langtags end |
Instance Method Details
#call(*available_langtags) ⇒ String, ...
Matches the user’s preferred languages against the available languages of your application. It prioritizes higher quality values and returns the most suitable match.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/accept_language/matcher.rb', line 46 def call(*) = drop_unacceptable(*) .each do |preferred_tag| if wildcard?(preferred_tag) langtag = any_other_langtag(*) return langtag unless langtag.nil? else .each do |available_langtag| return available_langtag if available_langtag.match?(/\A#{preferred_tag}/i) end end end nil end |