accept_language 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,387 +1,104 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AcceptLanguage
4
- # = Language Preference Matcher
5
- #
6
- # Matcher implements the language matching algorithm defined in RFC 2616
7
- # Section 14.4. It takes parsed language preferences (from {Parser}) and
8
- # determines the optimal language choice from a set of available languages.
9
- #
10
- # == Overview
11
- #
12
- # The matching process balances multiple factors:
13
- #
14
- # 1. **Quality values**: Higher q-values indicate stronger user preference
15
- # 2. **Declaration order**: Tie-breaker when q-values are equal
16
- # 3. **Prefix matching**: Allows +en+ to match +en-US+, +en-GB+, etc.
17
- # 4. **Wildcards**: The +*+ range matches any otherwise unmatched language
18
- # 5. **Exclusions**: Languages with +q=0+ are explicitly unacceptable
19
- #
20
- # == RFC 2616 Section 14.4 Compliance
21
- #
22
- # This implementation follows the Accept-Language matching rules:
23
- #
24
- # > A language-range matches a language-tag if it exactly equals the tag,
25
- # > or if it exactly equals a prefix of the tag such that the first tag
26
- # > character following the prefix is "-".
27
- #
28
- # This means:
29
- # - +en+ matches +en+, +en-US+, +en-GB+, +en-Latn-US+
30
- # - +en-US+ matches only +en-US+ (not +en+ or +en-GB+)
31
- # - +en+ does NOT match +eng+ (no hyphen boundary)
32
- #
33
- # == Quality Value Semantics
34
- #
35
- # Quality values have specific meanings per RFC 2616:
36
- #
37
- # - +q=1+ (or omitted): Most preferred
38
- # - +0 < q < 1+: Acceptable with relative preference
39
- # - +q=0+: Explicitly NOT acceptable
40
- #
41
- # The +q=0+ case is special: it doesn't just indicate low preference, it
42
- # completely excludes the language from consideration. This is used with
43
- # wildcards to express "any language except X":
44
- #
45
- # Accept-Language: *, en;q=0
46
- #
47
- # == Wildcard Behavior
48
- #
49
- # The wildcard +*+ matches any language not explicitly matched by another
50
- # language-range. When processing a wildcard:
51
- #
52
- # 1. Collect all explicitly listed language tags (excluding the wildcard)
53
- # 2. Find available languages that don't match any explicit tag
54
- # 3. Return the first such language
55
- #
56
- # This ensures explicit preferences always take priority over the wildcard.
57
- #
58
- # == Internal Design
59
- #
60
- # The Matcher separates languages into two categories during initialization:
61
- #
62
- # - **preferred_langtags**: Languages with q > 0, sorted by descending quality
63
- # - **excluded_langtags**: Languages with q = 0 (explicitly unacceptable)
64
- #
65
- # This separation optimizes the matching algorithm by allowing quick
66
- # filtering of excluded languages before attempting matches.
67
- #
68
- # == Thread Safety
69
- #
70
- # Matcher instances are immutable after initialization. Both +preferred_langtags+
71
- # and +excluded_langtags+ are frozen, making instances safe for concurrent use.
4
+ # Selects the best available language tag for the ranges of an
5
+ # +Accept-Language+ field, as specified by Sections 4 and 5 of
6
+ # SPECIFICATION.md.
7
+ #
8
+ # Every available tag is scored on its own, then the best score wins:
9
+ #
10
+ # 1. A range matches a tag it equals, or that it prefixes at a hyphen
11
+ # (Basic Filtering, RFC 4647 Section 3.3.1). <tt>*</tt> matches every
12
+ # tag.
13
+ # 2. The quality of a tag is the quality of the longest range matching it.
14
+ # <tt>*</tt> is the shortest range, so it only speaks for the tags no
15
+ # other range matches.
16
+ # 3. A tag is acceptable when a range matches it and its quality is
17
+ # positive.
18
+ # 4. The rank of a tag is the lowest position among the ranges that match
19
+ # it and carry its quality.
20
+ # 5. The acceptable tag with the highest quality wins. Ties go to the lowest
21
+ # rank, then to the earliest tag in the available list.
22
+ #
23
+ # The ranges of a field are unique, so the ranges matching a tag are found
24
+ # by looking up the tag and each of its prefixes, without scanning them.
72
25
  #
73
26
  # @api private
74
- # @note This class is used internally by {Parser#match} and should not be
75
- # instantiated directly. Use {AcceptLanguage.parse} followed by
76
- # {Parser#match} instead.
77
- #
78
- # @example Internal usage (via Parser)
79
- # # Don't do this:
80
- # matcher = AcceptLanguage::Matcher.new("en" => 1000, "fr" => 800)
81
- #
82
- # # Do this instead:
83
- # AcceptLanguage.parse("en, fr;q=0.8").match(:en, :fr)
84
- #
85
- # @see Parser#match
86
- # @see https://tools.ietf.org/html/rfc2616#section-14.4 RFC 2616 Section 14.4
87
- class Matcher
88
- # The hyphen character used as a subtag delimiter in BCP 47 language tags.
89
- #
90
- # Per RFC 2616 Section 14.4, prefix matching must respect hyphen boundaries.
91
- # A language-range matches a language-tag only if the character immediately
92
- # following the prefix is a hyphen.
93
- #
94
- # @api private
95
- # @return [String] "-"
96
- HYPHEN = "-"
97
-
98
- # Error message raised when an available language tag is not a Symbol.
99
- #
100
- # This guards against accidental non-Symbol values in the available languages
101
- # array, which would cause unexpected behavior during matching.
102
- #
103
- # @api private
104
- # @return [String]
105
- LANGTAG_TYPE_ERROR = "Language tag must be a Symbol"
106
-
107
- # The wildcard character that matches any language not explicitly listed.
108
- #
109
- # Per RFC 2616 Section 14.4, the wildcard has special semantics:
110
- # - It matches any language not matched by other ranges
111
- # - +*;q=0+ makes all unlisted languages unacceptable
112
- # - It has lower effective priority than explicit language tags
113
- #
114
- # @api private
115
- # @return [String] "*"
27
+ module Matcher
28
+ # The range that matches every tag.
116
29
  WILDCARD = "*"
117
30
 
118
- # Language tags explicitly marked as unacceptable (+q=0+).
119
- #
120
- # These tags are filtered out from available languages before any
121
- # matching occurs. Exclusions apply via prefix matching, so excluding
122
- # +en+ also excludes +en-US+, +en-GB+, etc.
123
- #
124
- # @note The wildcard +*+ is never added to this set, even when +*;q=0+
125
- # is specified. Wildcard exclusion is handled implicitly: when +*;q=0+
126
- # and no other languages have +q > 0+, the preferred_langtags list is
127
- # empty, resulting in no matches.
128
- #
129
- # @api private
130
- # @return [Set<String>] downcased language tags with q=0
131
- #
132
- # @example
133
- # # For "*, en;q=0, de;q=0"
134
- # matcher.excluded_langtags
135
- # # => #<Set: {"en", "de"}>
136
- attr_reader :excluded_langtags
137
-
138
- # Language tags sorted by preference (descending quality value).
139
- #
140
- # This array contains only tags with +q > 0+, ordered from most preferred
141
- # to least preferred. When quality values are equal, the original
142
- # declaration order from the Accept-Language header is preserved.
143
- #
144
- # The stable sort guarantee ensures deterministic matching: given the
145
- # same header and available languages, the result is always the same.
146
- #
147
- # @api private
148
- # @return [Array<String>] downcased language tags, highest quality first
149
- #
150
- # @example
151
- # # For "fr;q=0.8, en, de;q=0.9"
152
- # # Sorted: en (q=1), de (q=0.9), fr (q=0.8)
153
- # matcher.preferred_langtags
154
- # # => ["en", "de", "fr"]
155
- attr_reader :preferred_langtags
156
-
157
- # Creates a new Matcher instance from parsed language preferences.
158
- #
159
- # The initialization process:
160
- #
161
- # 1. Separates excluded tags (+q=0+) from preferred tags (+q > 0+)
162
- # 2. Sorts preferred tags by descending quality value
163
- # 3. Preserves original order for tags with equal quality (stable sort)
164
- #
165
- # == Exclusion Rules
166
- #
167
- # Only specific language tags with +q=0+ are added to the exclusion set.
168
- # The wildcard +*+ is explicitly NOT added even when +*;q=0+ is present,
169
- # because:
170
- #
171
- # - Adding +*+ to exclusions would break prefix matching logic
172
- # - +*;q=0+ semantics are: "no unlisted language is acceptable"
173
- # - This is achieved by having an empty preferred_langtags (no wildcards)
174
- #
175
- # == Stable Sorting
176
- #
177
- # Ruby's +sort_by+ is stable since Ruby 2.0, meaning elements with equal
178
- # sort keys maintain their relative order. This ensures that when multiple
179
- # languages have the same quality value, the first one declared in the
180
- # Accept-Language header wins.
181
- #
182
- # @api private
183
- # @param languages_range [Hash{String => Integer}] language tags mapped to
184
- # quality values (0-1000), as produced by {Parser}
185
- #
186
- # @example
187
- # Matcher.new("en" => 1000, "fr" => 800, "de" => 0)
188
- # # preferred_langtags: ["en", "fr"]
189
- # # excluded_langtags: #<Set: {"de"}>
190
- def initialize(**languages_range)
191
- @excluded_langtags = ::Set[]
192
-
193
- languages_range.each do |langtag, quality|
194
- next unless quality.zero? && !wildcard?(langtag)
31
+ # Separator of the subtags of a language tag.
32
+ HYPHEN = "-"
195
33
 
196
- # Exclude specific language tags, but NOT the wildcard.
197
- # When "*;q=0" is specified, all non-listed languages become
198
- # unacceptable implicitly (they won't match any preferred_langtags).
199
- # Adding "*" to excluded_langtags would break prefix_match? logic.
200
- @excluded_langtags << langtag
34
+ # Error message raised when the available language tags are not an Array.
35
+ LANGTAGS_TYPE_ERROR = "Available language tags must be an Array"
36
+
37
+ # Error message raised when an available language tag is neither a Symbol
38
+ # nor a String.
39
+ LANGTAG_TYPE_ERROR = "Language tag must be a Symbol or a String"
40
+
41
+ class << self
42
+ # @param ranges [Hash{String => Array(Integer, Integer)}] the ranges
43
+ # returned by {Parser.parse}
44
+ # @param available_langtags [Array<Symbol, String>] the supported
45
+ # languages
46
+ # @return [Symbol, String, nil] the best match, or +nil+
47
+ # @raise [TypeError] if +available_langtags+ is not an Array of Symbols
48
+ # or Strings
49
+ #
50
+ # @example
51
+ # Matcher.call({"en" => [1000, 0], "fr" => [800, 1]}, %i[fr en])
52
+ # # => :en
53
+ def call(ranges, available_langtags)
54
+ raise ::TypeError, LANGTAGS_TYPE_ERROR unless available_langtags.is_a?(::Array)
55
+
56
+ # Every tag is visited, so an invalid one raises whatever the ranges
57
+ # are. The index makes each key unique: on a tie, the earliest tag in
58
+ # the list wins.
59
+ candidates = available_langtags.each_with_index.filter_map do |langtag, index|
60
+ quality, priority = score(ranges, normalize(langtag))
61
+ [[quality, priority, -index], langtag] unless quality.nil?
62
+ end
63
+
64
+ candidates.max_by(&:first)&.last
201
65
  end
202
66
 
203
- # Sort by descending quality. Ruby's sort_by is stable, so languages
204
- # with identical quality values preserve their original order from
205
- # the Accept-Language header (first declared = higher priority).
206
- @preferred_langtags = languages_range
207
- .reject { |_, quality| quality.zero? }
208
- .sort_by { |_, quality| -quality }
209
- .map(&:first)
210
- end
211
-
212
- # Finds the best matching language from the available options.
213
- #
214
- # == Algorithm
215
- #
216
- # 1. **Filter**: Remove available languages that match any excluded tag
217
- # 2. **Match**: For each preferred tag (in quality order):
218
- # - If it's a wildcard, return the first available language not
219
- # matching any other preferred tag
220
- # - Otherwise, return the first available language that matches
221
- # via exact match or prefix match
222
- # 3. **Result**: Return the first match found, or +nil+ if none
223
- #
224
- # == Return Value
225
- #
226
- # The returned value preserves the exact form (case) of the matched
227
- # element from +available_langtags+. This is important for direct use
228
- # with APIs like +I18n.locale=+ that may be case-sensitive.
229
- #
230
- # @api private
231
- # @param available_langtags [Array<Symbol>] languages to match against
232
- # @return [Symbol, nil] the best matching language, or +nil+
233
- # @raise [TypeError] if any available language tag is not a Symbol
234
- #
235
- # @example Basic matching
236
- # matcher = Matcher.new("en" => 1000, "fr" => 800)
237
- # matcher.call(:en, :fr, :de)
238
- # # => :en
239
- #
240
- # @example Prefix matching
241
- # matcher = Matcher.new("en" => 1000)
242
- # matcher.call(:"en-US", :"en-GB")
243
- # # => :"en-US"
244
- #
245
- # @example With exclusion
246
- # matcher = Matcher.new("*" => 500, "en" => 0)
247
- # matcher.call(:en, :fr)
248
- # # => :fr
249
- def call(*available_langtags)
250
- filtered_tags = drop_unacceptable(*available_langtags)
251
- return if filtered_tags.empty?
252
-
253
- find_best_match(filtered_tags)
254
- end
67
+ private
255
68
 
256
- private
69
+ # The form of a tag used for matching: its bytes, lowercased. Like the
70
+ # field, a tag is handled as bytes, so that no encoding can raise.
71
+ def normalize(langtag)
72
+ raise ::TypeError, LANGTAG_TYPE_ERROR unless langtag.is_a?(::Symbol) || langtag.is_a?(::String)
257
73
 
258
- # Iterates through preferred languages to find the first match.
259
- #
260
- # @param available_langtags [Set<String>] pre-filtered available tags
261
- # @return [Symbol, nil] the matched tag or nil
262
- def find_best_match(available_langtags)
263
- preferred_langtags.each do |preferred_tag|
264
- match = match_langtag(preferred_tag, available_langtags)
265
- return :"#{match}" unless match.nil?
74
+ langtag.to_s.b.downcase(:ascii)
266
75
  end
267
76
 
268
- nil
269
- end
77
+ # The score of a tag is <tt>[quality, -rank]</tt>, so that the best
78
+ # score is the greatest. An unacceptable tag has no score.
79
+ def score(ranges, tag)
80
+ weights = matching(ranges, tag)
81
+ quality = weights.first&.first
82
+ return if quality.nil? || quality.zero?
270
83
 
271
- # Attempts to match a single preferred tag against available languages.
272
- #
273
- # Handles both wildcard and specific language tags differently.
274
- #
275
- # @param preferred_tag [String] the preferred language tag to match
276
- # @param available_langtags [Set<String>] available tags to search
277
- # @return [String, nil] the matched tag or nil
278
- def match_langtag(preferred_tag, available_langtags)
279
- if wildcard?(preferred_tag)
280
- any_other_langtag(*available_langtags)
281
- else
282
- find_matching_tag(preferred_tag, available_langtags)
84
+ rank = weights.filter_map { |range_quality, position| position if range_quality == quality }.min
85
+ [quality, -rank]
283
86
  end
284
- end
285
87
 
286
- # Finds an available language that matches via exact or prefix match.
287
- #
288
- # @param preferred_tag [String] the preferred tag (downcased)
289
- # @param available_langtags [Set<String>] available tags
290
- # @return [String, nil] the first matching tag or nil
291
- def find_matching_tag(preferred_tag, available_langtags)
292
- available_langtags.find { |tag| prefix_match?(preferred_tag, tag) }
293
- end
294
-
295
- # Finds an available language for wildcard matching.
296
- #
297
- # Returns the first available language that doesn't match any explicitly
298
- # listed preferred language tag. This implements the RFC 2616 semantics
299
- # where +*+ matches "any language not matched by another range".
300
- #
301
- # @param available_langtags [Array<String>] available tags
302
- # @return [String, nil] the first non-matching tag or nil
303
- def any_other_langtag(*available_langtags)
304
- langtags = preferred_langtags - [WILDCARD]
305
-
306
- available_langtags.find do |available_langtag|
307
- langtags.none? { |tag| prefix_match?(tag, available_langtag) }
88
+ # The weights of the ranges matching a tag, longest range first. The
89
+ # wildcard is one of them only when no other range matches.
90
+ def matching(ranges, tag)
91
+ weights = prefixes(tag).filter_map { |prefix| ranges[prefix] }
92
+ weights.empty? ? [ranges[WILDCARD]].compact : weights
308
93
  end
309
- end
310
-
311
- # Removes explicitly excluded languages from the available set.
312
- #
313
- # Uses prefix matching for exclusions, so excluding +en+ also excludes
314
- # +en-US+, +en-GB+, etc.
315
- #
316
- # @param available_langtags [Array<Symbol>] all available tags
317
- # @return [Set<String>] tags not matching any exclusion
318
- # @raise [TypeError] if any tag is not a Symbol
319
- def drop_unacceptable(*available_langtags)
320
- available_langtags.each_with_object(::Set[]) do |available_langtag, langtags|
321
- raise ::TypeError, LANGTAG_TYPE_ERROR unless available_langtag.is_a?(::Symbol)
322
94
 
323
- available_langtag = "#{available_langtag}"
324
- langtags << available_langtag unless unacceptable?(available_langtag)
95
+ # The tag and its prefixes ending before a hyphen, longest first:
96
+ # "zh-hant-tw" gives ["zh-hant-tw", "zh-hant", "zh"]. These are the
97
+ # only ranges that can match the tag.
98
+ def prefixes(tag)
99
+ subtags = tag.split(HYPHEN, -1)
100
+ subtags.size.downto(1).map { |size| subtags.first(size).join(HYPHEN) }
325
101
  end
326
102
  end
327
-
328
- # Checks if a language tag is explicitly excluded.
329
- #
330
- # @param langtag [String] the tag to check (as string)
331
- # @return [Boolean] true if the tag matches any exclusion
332
- def unacceptable?(langtag)
333
- excluded_langtags.any? { |excluded_tag| prefix_match?(excluded_tag, langtag) }
334
- end
335
-
336
- # Checks if a value is the wildcard character.
337
- #
338
- # @param value [String] the value to check
339
- # @return [Boolean] true if the value is "*"
340
- def wildcard?(value)
341
- value.eql?(WILDCARD)
342
- end
343
-
344
- # Implements RFC 2616 Section 14.4 prefix matching rule.
345
- #
346
- # From the specification:
347
- #
348
- # > A language-range matches a language-tag if it exactly equals the tag,
349
- # > or if it exactly equals a prefix of the tag such that the first tag
350
- # > character following the prefix is "-".
351
- #
352
- # This rule ensures that language ranges match at subtag boundaries:
353
- #
354
- # - +en+ matches +en+ (exact)
355
- # - +en+ matches +en-US+ (prefix + hyphen)
356
- # - +en+ does NOT match +eng+ (no hyphen after prefix)
357
- # - +en-US+ does NOT match +en+ (prefix is longer than tag)
358
- #
359
- # Matching is case-insensitive per RFC 2616, using +casecmp?+ for
360
- # efficient comparison without allocating new strings.
361
- #
362
- # @param prefix [String] the language-range to match (downcased)
363
- # @param tag [String] the language-tag to test (any case)
364
- # @return [Boolean] true if prefix matches tag per RFC 2616 rules
365
- #
366
- # @example Exact matches
367
- # prefix_match?("en", "en") # => true
368
- # prefix_match?("en", "EN") # => true
369
- # prefix_match?("en-us", "en-US") # => true
370
- #
371
- # @example Prefix matches
372
- # prefix_match?("en", "en-us") # => true
373
- # prefix_match?("en", "en-GB") # => true
374
- # prefix_match?("zh", "zh-Hant-TW") # => true
375
- #
376
- # @example Non-matches
377
- # prefix_match?("en-us", "en") # => false (prefix longer than tag)
378
- # prefix_match?("en", "eng") # => false (no hyphen boundary)
379
- # prefix_match?("en", "fr") # => false (different language)
380
- def prefix_match?(prefix, tag)
381
- return true if tag.casecmp?(prefix)
382
- return false if tag.length <= prefix.length
383
-
384
- tag[0, prefix.length].casecmp?(prefix) && tag[prefix.length] == HYPHEN
385
- end
386
103
  end
387
104
  end