accept_language 2.1.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c1d4f90fc40c062ac4f250c1c3b8ac8540796b232cf63b7d5c25b5e2e3c9124e
4
- data.tar.gz: 150bb9def9e5f4799c432df6d6c364fedf88132b117d28e79a6ed44f467dcc70
3
+ metadata.gz: 19552c2e3b6929343c09e75698eeba19519dc01ceeeccb61772dd2c4d0a7c035
4
+ data.tar.gz: 2c49770f88fc6062d35ec8a628315e88b689106fcfd78022196b8ba3c773840e
5
5
  SHA512:
6
- metadata.gz: 537d924a23dc3c0fe8fb523556a6da653e16471b6b8ca94e0ee57f36fa1d6842103e380c3ea1e2dbd468b06a65a698ecdbf8923235f4eac0031a52801ba446f8
7
- data.tar.gz: 8e48f57d2f0a4005483d29cf5503accc39eecffe19f78e8848dfa216422d1b2792f50cc5199c938674a483ef90ca20127fbfe452c0eebae9e30b36d7b8dc0bc2
6
+ metadata.gz: 8b6f799e3e6712c01254f1e54d6deb361f0eeeb93a62c4873e13ae290a4c04420d6a35ddcb0e14ea16997fbb64b92a450796c51de900ab1fbbce08ec3d6f6716
7
+ data.tar.gz: cc26685a4b373d06ed53314916be9fac233cec1eeab497c6d69142711abff9573e69c65c2983c27267ff680985f63fad4fe35de555644e19b1762841287cef5b
data/README.md CHANGED
@@ -1,93 +1,246 @@
1
1
  # AcceptLanguage
2
2
 
3
- A lightweight, thread-safe Ruby library for parsing `Accept-Language` HTTP headers as defined in [RFC 2616](https://tools.ietf.org/html/rfc2616#section-14.4), with full support for [BCP 47](https://tools.ietf.org/html/bcp47) language tags.
4
-
5
3
  [![Version](https://img.shields.io/github/v/tag/cyril/accept_language.rb?label=Version&logo=github)](https://github.com/cyril/accept_language.rb/tags)
6
4
  [![Yard documentation](https://img.shields.io/badge/Yard-documentation-blue.svg?logo=github)](https://rubydoc.info/github/cyril/accept_language.rb/main)
7
5
  ![Ruby](https://github.com/cyril/accept_language.rb/actions/workflows/ruby.yml/badge.svg?branch=main)
8
6
  ![RuboCop](https://github.com/cyril/accept_language.rb/actions/workflows/rubocop.yml/badge.svg?branch=main)
9
7
  [![License](https://img.shields.io/github/license/cyril/accept_language.rb?label=License&logo=github)](https://github.com/cyril/accept_language.rb/raw/main/LICENSE.md)
10
8
 
11
- ## Features
9
+ A lightweight, thread-safe Ruby library for parsing the `Accept-Language` HTTP header field.
10
+
11
+ This implementation conforms to:
12
+
13
+ - [RFC 9110 Section 12.5.4](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.4) — Accept-Language header field definition
14
+ - [RFC 9110 Section 12.4.2](https://www.rfc-editor.org/rfc/rfc9110#section-12.4.2) — Quality values syntax
15
+ - [RFC 4647 Section 3.3.1](https://www.rfc-editor.org/rfc/rfc4647#section-3.3.1) — Basic Filtering matching scheme
16
+ - [BCP 47](https://www.rfc-editor.org/info/bcp47) — Tags for Identifying Languages
12
17
 
13
- - Thread-safe
14
- - No framework dependencies
15
- - Case-insensitive matching
16
- - BCP 47 language tag support
17
- - Wildcard and exclusion handling
18
+ Its behavior is defined by a [specification](SPECIFICATION.md) and a set of test vectors shared with the [Elixir implementation](https://github.com/cyril/accept_language.ex): both return the same result for the same input.
18
19
 
19
20
  ## Installation
20
21
 
21
22
  ```ruby
22
- gem "accept_language"
23
+ gem "accept_language", "~> 3.0"
23
24
  ```
24
25
 
26
+ Ruby 3.3 or later is required.
27
+
28
+ Version 3 replaces `AcceptLanguage.parse(header).match(*locales)` with `AcceptLanguage.negotiate(header, locales)`. See [Upgrading from 2.x](#upgrading-from-2x).
29
+
25
30
  ## Usage
26
31
 
32
+ `AcceptLanguage.negotiate` takes the value of the header and the languages your application supports. It returns the supported language the user prefers, or `nil` when none is acceptable:
33
+
34
+ ```ruby
35
+ AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %i[en da])
36
+ # => :da
37
+
38
+ AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %i[fr de])
39
+ # => nil
40
+
41
+ AcceptLanguage.negotiate(nil, %i[en da]) || :en
42
+ # => :en (no header: fall back to a default)
43
+ ```
44
+
45
+ The supported languages are an Array of Symbols or Strings, such as `I18n.available_locales`. The result is one of them, exactly as given:
46
+
27
47
  ```ruby
28
- AcceptLanguage.parse("en-GB, en;q=0.9").match(:en, :"en-GB")
29
- # => :"en-GB"
48
+ AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %w[en da])
49
+ # => "da"
30
50
  ```
31
51
 
52
+ The library keeps no state and is safe to call from any thread. No part of the header is ever turned into a Symbol.
53
+
54
+ ## Behavior
55
+
32
56
  ### Quality values
33
57
 
34
- Quality values (q-values) indicate preference order from 0 to 1:
58
+ Quality values (q-values) indicate relative preference, ranging from `0` (not acceptable) to `1` (most preferred). When omitted, the default is `1`.
59
+
60
+ ```ruby
61
+ AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %i[en da])
62
+ # => :da (q=1 beats q=0.8)
63
+
64
+ AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %i[en en-GB])
65
+ # => :"en-GB" (q=0.8 beats q=0.7)
66
+ ```
67
+
68
+ Per RFC 9110 Section 12.4.2, a q-value has at most three decimal places: `0`, `0.7`, `0.85`, `1.000`. A trailing dot without digits (`0.`, `1.`) is allowed by the grammar and accepted.
69
+
70
+ ### Basic Filtering
71
+
72
+ A language range matches a language tag if, in a case-insensitive comparison, it exactly equals the tag, or if it exactly equals a prefix of the tag such that the first character following the prefix is `-` (RFC 4647 Section 3.3.1).
73
+
74
+ ```ruby
75
+ AcceptLanguage.negotiate("zh", %i[zh-TW])
76
+ # => :"zh-TW" ("zh" matches "zh-TW")
77
+
78
+ AcceptLanguage.negotiate("zh", %i[zhx])
79
+ # => nil ("zh" does not match "zhx", a different language)
80
+
81
+ AcceptLanguage.negotiate("zh-TW", %i[zh])
82
+ # => nil (a specific range does not match a less specific tag)
83
+
84
+ AcceptLanguage.negotiate("de-de", %i[de-DE-1996])
85
+ # => :"de-DE-1996"
86
+
87
+ AcceptLanguage.negotiate("de-de", %i[de-Latn-DE])
88
+ # => nil ("de-de" is not a prefix of "de-Latn-DE")
89
+ ```
90
+
91
+ ### Longest match
92
+
93
+ When several ranges match the same tag, the longest one decides the tag's q-value, so that a specific range overrides a general one.
94
+
95
+ ```ruby
96
+ AcceptLanguage.negotiate("en-US, en;q=0", %i[en-GB en-US])
97
+ # => :"en-US" ("en-US" takes q=1 from its own range, "en-GB" takes q=0 from "en")
98
+
99
+ AcceptLanguage.negotiate("en;q=0.9, en-US;q=0.5", %i[en-US en-GB])
100
+ # => :"en-GB" ("en-US" takes q=0.5 from its own range, "en-GB" takes q=0.9 from "en")
101
+ ```
102
+
103
+ This is the rule RFC 2616 Section 14.4 spelled out ("the quality value of the longest language-range in the field that matches the language-tag"). Later revisions of HTTP dropped the sentence without replacing it.
104
+
105
+ ### Wildcards
106
+
107
+ The wildcard `*` matches every tag and counts as the shortest range: it only speaks for the tags no other range matches.
108
+
109
+ ```ruby
110
+ AcceptLanguage.negotiate("de, *;q=0.5", %i[ja])
111
+ # => :ja (matched by the wildcard)
112
+
113
+ AcceptLanguage.negotiate("de, *;q=0.5", %i[ja de])
114
+ # => :de ("de" has q=1, "ja" has q=0.5)
115
+ ```
116
+
117
+ ### Exclusions
118
+
119
+ A q-value of `0` marks a language as not acceptable. It applies to the tags the range matches, unless a longer range claims them (see [Longest match](#longest-match)).
120
+
121
+ ```ruby
122
+ AcceptLanguage.negotiate("*, en;q=0", %i[en en-GB])
123
+ # => nil (English is excluded, with its variants)
124
+
125
+ AcceptLanguage.negotiate("*, en;q=0", %i[en ja])
126
+ # => :ja
127
+
128
+ AcceptLanguage.negotiate("*, en;q=0, en-GB", %i[en en-GB])
129
+ # => :"en-GB" ("en-GB" is the longest match and takes q=1)
130
+ ```
131
+
132
+ ### Ties
133
+
134
+ Among acceptable tags, the highest q-value wins. When several tags share it, the one whose range comes first in the header wins:
135
+
136
+ ```ruby
137
+ AcceptLanguage.negotiate("en;q=0.8, fr;q=0.8", %i[fr en])
138
+ # => :en (declared first)
139
+
140
+ AcceptLanguage.negotiate("fr;q=0.8, en;q=0.8", %i[en fr])
141
+ # => :fr (declared first)
142
+ ```
143
+
144
+ A tag is ranked by the earliest range that matches it with its q-value, so adding a more specific range for a language the header already prefers never demotes that language. If a tie remains, the order of the available languages decides:
35
145
 
36
146
  ```ruby
37
- parser = AcceptLanguage.parse("da, en-GB;q=0.8, en;q=0.7")
147
+ AcceptLanguage.negotiate("en, fr, en-US", %i[fr en-US])
148
+ # => :"en-US" (q=1 was stated for "en-US" by "en", first in the header)
38
149
 
39
- parser.match(:en, :da) # => :da
40
- parser.match(:en, :"en-GB") # => :"en-GB"
41
- parser.match(:fr) # => nil
150
+ AcceptLanguage.negotiate("en", %i[en-GB en-US])
151
+ # => :"en-GB" (same range, same q-value: first available)
42
152
  ```
43
153
 
44
- ### Language variants
154
+ ### Case insensitivity
45
155
 
46
- A generic language tag matches its regional variants, but not the reverse:
156
+ Matching ignores case, and the result keeps the case of the available tag:
47
157
 
48
158
  ```ruby
49
- AcceptLanguage.parse("fr").match(:"fr-CH") # => :"fr-CH"
50
- AcceptLanguage.parse("fr-CH").match(:fr) # => nil
159
+ AcceptLanguage.negotiate("EN-GB", %i[en-gb])
160
+ # => :"en-gb"
161
+
162
+ AcceptLanguage.negotiate("en-gb", %w[EN-GB])
163
+ # => "EN-GB"
51
164
  ```
52
165
 
53
- ### Wildcards and exclusions
166
+ ### Repeated ranges
54
167
 
55
- The wildcard `*` matches any language. A q-value of 0 explicitly excludes a language:
168
+ HTTP gives no meaning to a range listed more than once. A single occurrence is retained: an exclusion (`q=0`) if there is one, otherwise the highest q-value.
56
169
 
57
170
  ```ruby
58
- AcceptLanguage.parse("de-DE, *;q=0.5").match(:fr) # => :fr
59
- AcceptLanguage.parse("*, en;q=0").match(:en) # => nil
60
- AcceptLanguage.parse("*, en;q=0").match(:fr) # => :fr
171
+ AcceptLanguage.negotiate("en;q=0, fr, en", %i[en fr])
172
+ # => :fr (the exclusion of "en" wins)
173
+
174
+ AcceptLanguage.negotiate("en;q=0.5, fr;q=0.8, en;q=0.9", %i[en fr])
175
+ # => :en ("en" is considered at q=0.9)
176
+
177
+ AcceptLanguage.negotiate("*, *;q=0", %i[fr])
178
+ # => nil
61
179
  ```
62
180
 
63
- ### Case sensitivity
181
+ ### Malformed elements
64
182
 
65
- Matching is case-insensitive but preserves the case of the available language tag:
183
+ The header comes from the client and is handled as untrusted bytes, whatever the encoding of the String. An element that does not follow the grammar is ignored, and the rest of the header is still used. This is the case when:
184
+
185
+ - its language range is not a valid basic language range (`en_US`, `123`, `toolongprimary`, any non-ASCII character)
186
+ - its q-value is out of range, has more than three decimals, or is abbreviated (`1.5`, `0.1234`, `.5`)
187
+ - its q-value is empty (`en;q=`), or it carries anything but a single weight (`en;q=0.8;q=0.1`, `en;level=1`)
188
+ - it contains whitespace where the grammar allows none (`e n`, `en;q= 0.8`); spaces and tabs are only allowed around `,` and `;`
66
189
 
67
190
  ```ruby
68
- AcceptLanguage.parse("en-GB").match("en-gb") # => "en-gb"
69
- AcceptLanguage.parse("en-gb").match("en-GB") # => "en-GB"
191
+ AcceptLanguage.negotiate("en;q=, fr;q=0.5", %i[en fr])
192
+ # => :fr ("en;q=" is ignored; it does not default to q=1)
70
193
  ```
71
194
 
72
- ### BCP 47 support
195
+ ### Limits
196
+
197
+ Two limits bound the work done for a single header. They are far above legitimate usage (browsers send 2 to 10 ranges in under 200 bytes):
198
+
199
+ - a header longer than 4096 bytes is treated as absent, and `negotiate` returns `nil`
200
+ - only the first 50 elements of a header are considered
73
201
 
74
- This library supports [BCP 47](https://tools.ietf.org/html/bcp47) language tags, including:
202
+ ### BCP 47 language tags
75
203
 
76
- - **Script subtags**: `zh-Hans` (Simplified Chinese), `zh-Hant` (Traditional Chinese)
77
- - **Region subtags**: `en-US`, `pt-BR`
78
- - **Variant subtags**: `sl-nedis` (Slovenian Nadiza dialect), `de-1996` (German orthography reform)
204
+ Script, region and variant subtags are supported:
79
205
 
80
206
  ```ruby
81
- # Script variants
82
- AcceptLanguage.parse("zh-Hans").match(:"zh-Hans-CN", :"zh-Hant-TW")
83
- # => :"zh-Hans-CN"
207
+ # Script subtags
208
+ AcceptLanguage.negotiate("zh-Hant, zh-Hans;q=0.9", %i[zh-Hans-CN zh-Hant-TW])
209
+ # => :"zh-Hant-TW"
84
210
 
85
- # Orthography variants (numeric subtags)
86
- AcceptLanguage.parse("de-1996, de;q=0.9").match(:"de-CH-1996", :"de-CH")
211
+ # Variant subtags
212
+ AcceptLanguage.negotiate("de-CH-1996, de-CH;q=0.9", %i[de-CH de-CH-1996])
87
213
  # => :"de-CH-1996"
88
214
  ```
89
215
 
90
- ## Rails integration
216
+ The available tags are not validated: they are compared as they are. A tag such as `:pt_BR`, which no language range can equal or prefix, can only be matched by `*`.
217
+
218
+ ### Errors
219
+
220
+ The arguments are checked on every call, including when the header is `nil`, so that a misuse shows up on the first request. `negotiate` raises `TypeError` when the header is neither a String nor `nil`, or when the available languages are not an Array of Symbols or Strings.
221
+
222
+ ## Integration examples
223
+
224
+ ### Rack
225
+
226
+ ```ruby
227
+ # config.ru
228
+ class LocaleMiddleware
229
+ def initialize(app, available_locales:, default_locale:)
230
+ @app = app
231
+ @available_locales = available_locales
232
+ @default_locale = default_locale
233
+ end
234
+
235
+ def call(env)
236
+ header = env["HTTP_ACCEPT_LANGUAGE"]
237
+ env["rack.locale"] = AcceptLanguage.negotiate(header, @available_locales) || @default_locale
238
+ @app.call(env)
239
+ end
240
+ end
241
+ ```
242
+
243
+ ### Ruby on Rails
91
244
 
92
245
  ```ruby
93
246
  # app/controllers/application_controller.rb
@@ -99,32 +252,79 @@ class ApplicationController < ActionController::Base
99
252
  end
100
253
 
101
254
  def best_locale_from_request
102
- # HTTP_ACCEPT_LANGUAGE is the standardized key for the Accept-Language header in Rack/Rails
103
- return I18n.default_locale unless request.headers.key?("HTTP_ACCEPT_LANGUAGE")
104
-
105
- string = request.headers.fetch("HTTP_ACCEPT_LANGUAGE")
106
- locale = AcceptLanguage.parse(string).match(*I18n.available_locales)
255
+ # HTTP_ACCEPT_LANGUAGE is the standardized key for the Accept-Language header in Rack/Rails.
256
+ # Its value is nil when the request has no such header.
257
+ header = request.headers["HTTP_ACCEPT_LANGUAGE"]
107
258
 
108
259
  # If the server cannot serve any matching language,
109
260
  # it can theoretically send back a 406 (Not Acceptable) error code.
110
261
  # But, for a better user experience, this is rarely done and more
111
262
  # common way is to ignore the Accept-Language header in this case.
112
- return I18n.default_locale if locale.nil?
113
-
114
- locale
263
+ AcceptLanguage.negotiate(header, I18n.available_locales) || I18n.default_locale
115
264
  end
116
265
  end
117
266
  ```
118
267
 
268
+ ## Upgrading from 2.x
269
+
270
+ Replace the two-step call with a single one, and pass the available languages as an Array:
271
+
272
+ ```ruby
273
+ # 2.x
274
+ AcceptLanguage.parse(header).match(*I18n.available_locales)
275
+
276
+ # 3.x
277
+ AcceptLanguage.negotiate(header, I18n.available_locales)
278
+ ```
279
+
280
+ `AcceptLanguage.parse`, `AcceptLanguage::Parser` and `AcceptLanguage::Matcher` are no longer part of the public interface.
281
+
282
+ A few results change, all of them for headers that browsers do not send by default. The [changelog](CHANGELOG.md) lists them; the main ones are:
283
+
284
+ - a specific range now overrides a general one: `en-US, en;q=0` accepts `en-US` (it accepted no English at all)
285
+ - `en;q=` is ignored (it was read as `en`), and so is `e n` (it was read as `en`)
286
+ - a tab is accepted wherever a space is (the element next to it was ignored)
287
+ - a header longer than 4096 bytes is treated as absent, and elements after the 50th are ignored
288
+
289
+ ## Standards compliance
290
+
291
+ ### Supported specifications
292
+
293
+ | Specification | Description | Status |
294
+ |---------------|-------------|--------|
295
+ | RFC 9110 §12.5.4 | Accept-Language header field | ✅ Supported |
296
+ | RFC 9110 §12.4.2 | Quality values (qvalues) | ✅ Supported |
297
+ | RFC 9110 §5.6.3 | Optional whitespace (OWS) | ✅ Supported |
298
+ | RFC 4647 §2.1 | Basic Language Range syntax | ✅ Supported |
299
+ | RFC 4647 §3.3.1 | Basic Filtering scheme | ✅ Supported |
300
+ | RFC 2616 §14.4 | Longest matching range decides a tag's q-value | ✅ Followed (the rule was dropped from later HTTP revisions without replacement) |
301
+ | BCP 47 | Language tag structure | ✅ Supported |
302
+
303
+ RFC 9110 obsoletes [RFC 7231](https://www.rfc-editor.org/rfc/rfc7231), which itself obsoleted [RFC 2616](https://www.rfc-editor.org/rfc/rfc2616). The header syntax is unchanged across these revisions.
304
+
305
+ ### Not implemented
306
+
307
+ | Specification | Description | Reason |
308
+ |---------------|-------------|--------|
309
+ | RFC 4647 §2.2 | Extended Language Range | Not used by HTTP |
310
+ | RFC 4647 §3.3.2 | Extended Filtering | Not used by HTTP |
311
+ | RFC 4647 §3.4 | Lookup scheme | Design choice — Basic Filtering is the scheme HTTP has always described |
312
+
119
313
  ## Documentation
120
314
 
121
- - [API Documentation](https://rubydoc.info/github/cyril/accept_language.rb/main)
122
- - [Language negotiation with Ruby](https://dev.to/cyri_/language-negotiation-with-ruby-5166)
123
- - [Rubyで言語ネゴシエーション](https://qiita.com/cyril/items/45dc233edb7be9d614e7)
315
+ - [API documentation](https://rubydoc.info/github/cyril/accept_language.rb/main)
316
+ - [Specification](SPECIFICATION.md) and [test vectors](spec/vectors.tsv) shared with the Elixir implementation
317
+ - [RFC 9110 — HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110)
318
+ - [RFC 4647 — Matching of Language Tags](https://www.rfc-editor.org/rfc/rfc4647)
319
+ - [BCP 47 — Tags for Identifying Languages](https://www.rfc-editor.org/info/bcp47)
320
+
321
+ ## See also
322
+
323
+ - [accept_language.ex](https://github.com/cyril/accept_language.ex) — Elixir equivalent of this library
124
324
 
125
325
  ## Versioning
126
326
 
127
- This library follows [Semantic Versioning 2.0.0](https://semver.org/).
327
+ This library follows [Semantic Versioning 2.0](https://semver.org/).
128
328
 
129
329
  ## License
130
330
 
@@ -1,107 +1,104 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AcceptLanguage
4
- # Matches Accept-Language header values against application-supported languages to determine
5
- # the optimal language choice. Handles quality values, wildcards, and language tag matching
6
- # according to RFC 2616 specifications.
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.
7
25
  #
8
26
  # @api private
9
- # @note This class is intended for internal use by {Parser} and should not be instantiated directly.
10
- class Matcher
11
- # @api private
27
+ module Matcher
28
+ # The range that matches every tag.
12
29
  WILDCARD = "*"
13
30
 
14
- # @api private
15
- attr_reader :excluded_langtags, :preferred_langtags
16
-
17
- # @api private
18
- def initialize(**languages_range)
19
- @excluded_langtags = ::Set[]
20
- langtags = []
21
-
22
- languages_range.select do |langtag, quality|
23
- if quality.zero?
24
- # Exclude specific language tags, but NOT the wildcard.
25
- # When "*;q=0" is specified, all non-listed languages become
26
- # unacceptable implicitly (they won't match any preferred_langtags).
27
- # Adding "*" to excluded_langtags would break prefix_match? logic.
28
- @excluded_langtags << langtag unless wildcard?(langtag)
29
- else
30
- level = (quality * 1_000).to_i
31
- langtags[level] = langtag
31
+ # Separator of the subtags of a language tag.
32
+ HYPHEN = "-"
33
+
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?
32
62
  end
33
- end
34
63
 
35
- @preferred_langtags = langtags.compact.reverse
36
- end
37
-
38
- # @api private
39
- def call(*available_langtags)
40
- raise ::ArgumentError, "Language tags cannot be nil" if available_langtags.any?(&:nil?)
41
-
42
- filtered_tags = drop_unacceptable(*available_langtags)
43
- return nil if filtered_tags.empty?
64
+ candidates.max_by(&:first)&.last
65
+ end
44
66
 
45
- find_best_match(filtered_tags)
46
- end
67
+ private
47
68
 
48
- 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)
49
73
 
50
- def find_best_match(available_langtags)
51
- preferred_langtags.each do |preferred_tag|
52
- match = match_langtag(preferred_tag, available_langtags)
53
- return match if match
74
+ langtag.to_s.b.downcase(:ascii)
54
75
  end
55
76
 
56
- nil
57
- 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?
58
83
 
59
- def match_langtag(preferred_tag, available_langtags)
60
- if wildcard?(preferred_tag)
61
- any_other_langtag(*available_langtags)
62
- else
63
- find_matching_tag(preferred_tag, available_langtags)
84
+ rank = weights.filter_map { |range_quality, position| position if range_quality == quality }.min
85
+ [quality, -rank]
64
86
  end
65
- end
66
-
67
- def find_matching_tag(preferred_tag, available_langtags)
68
- available_langtags.find { |tag| prefix_match?(preferred_tag, String(tag.downcase)) }
69
- end
70
87
 
71
- def any_other_langtag(*available_langtags)
72
- langtags = preferred_langtags - [WILDCARD]
73
-
74
- available_langtags.find do |available_langtag|
75
- available_downcased = available_langtag.downcase
76
- langtags.none? { |tag| prefix_match?(tag, String(available_downcased)) }
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
77
93
  end
78
- end
79
94
 
80
- def drop_unacceptable(*available_langtags)
81
- available_langtags.each_with_object(::Set[]) do |available_langtag, langtags|
82
- 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) }
83
101
  end
84
102
  end
85
-
86
- def unacceptable?(langtag)
87
- langtag_downcased = langtag.downcase
88
- excluded_langtags.any? { |excluded_tag| prefix_match?(excluded_tag, String(langtag_downcased)) }
89
- end
90
-
91
- def wildcard?(value)
92
- value.eql?(WILDCARD)
93
- end
94
-
95
- # Implements RFC 2616 Section 14.4 prefix matching rule:
96
- # "A language-range matches a language-tag if it exactly equals the tag,
97
- # or if it exactly equals a prefix of the tag such that the first tag
98
- # character following the prefix is '-'."
99
- #
100
- # @param prefix [String] The language-range to match (downcased)
101
- # @param tag [String] The language-tag to test (downcased)
102
- # @return [Boolean] true if prefix matches tag per RFC 2616 rules
103
- def prefix_match?(prefix, tag)
104
- tag == prefix || tag.start_with?("#{prefix}-")
105
- end
106
103
  end
107
104
  end
@@ -1,93 +1,109 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "bigdecimal"
4
-
5
3
  module AcceptLanguage
6
- # Parses Accept-Language header fields into structured data, extracting language tags
7
- # and their quality values (q-values). Validates input according to RFC 2616 specifications
8
- # and handles edge cases like malformed inputs and implicit quality values.
4
+ # Parses an +Accept-Language+ field value (RFC 9110 Section 12.5.4) into the
5
+ # ranges {Matcher} works with, as specified by Section 3 of
6
+ # SPECIFICATION.md.
7
+ #
8
+ # The result maps each language range, lowercased, to
9
+ # <tt>[quality, position]</tt>:
10
+ #
11
+ # - +quality+ is the qvalue as an Integer from 0 to 1000 (1000 when the
12
+ # weight is omitted), which keeps comparisons exact;
13
+ # - +position+ is the zero-based index of the element in the field, the
14
+ # tie-breaker between ranges of equal quality.
9
15
  #
10
- # @example
11
- # parser = Parser.new("da, en-GB;q=0.8, en;q=0.7")
12
- # parser.match(:en, :da) # => :da
16
+ # The field is handled as bytes. Invalid elements are ignored, and no String
17
+ # makes the parser raise.
13
18
  #
14
- # @see https://tools.ietf.org/html/rfc2616#section-14.4
15
- class Parser
16
- # @api private
17
- DEFAULT_QUALITY = "1"
18
- # @api private
19
+ # @api private
20
+ module Parser
21
+ # A field longer than this is treated as absent.
22
+ MAX_FIELD_BYTES = 4096
23
+
24
+ # Only the first elements of a field are considered.
25
+ MAX_ELEMENTS = 50
26
+
27
+ # Quality of a range that carries no weight.
28
+ DEFAULT_QUALITY = 1000
29
+
30
+ # Separator of the elements of a field.
19
31
  SEPARATOR = ","
20
- # @api private
21
- SPACE = " "
22
- # @api private
23
- SUFFIX = ";q="
24
- # @api private
25
- # RFC 2616 Section 3.9 qvalue syntax:
26
- # qvalue = ( "0" [ "." 0*3DIGIT ] ) | ( "1" [ "." 0*3("0") ] )
27
- QVALUE_PATTERN = /\A(?:0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?)\z/
28
- # @api private
29
- # Language tag pattern supporting BCP 47 (RFC 5646) alphanumeric subtags.
30
- #
31
- # RFC 2616 Section 3.10 references RFC 1766, which only allowed ALPHA in subtags.
32
- # However, BCP 47 (the current standard) permits alphanumeric subtags:
33
- # subtag = 1*8alphanum
34
- # alphanum = ALPHA / DIGIT
35
- #
36
- # Examples of valid BCP 47 tags with numeric subtags:
37
- # - "de-CH-1996" (German, Switzerland, orthography variant 1996)
38
- # - "sl-IT-nedis" (Slovenian, Italy, Nadiza dialect)
39
- # - "zh-Hans-CN" (Chinese, Simplified script, China)
40
- LANGTAG_PATTERN = /\A(?:\*|[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*)\z/
41
32
 
42
- # @api private
43
- # @return [Hash<String, BigDecimal>] Parsed language tags and their quality values
44
- attr_reader :languages_range
33
+ # Decimal point of a qvalue.
34
+ DOT = "."
45
35
 
46
- # Initializes a new Parser instance by importing and processing the given Accept-Language header field.
47
- #
48
- # @param field [String] The Accept-Language header field to parse.
49
- def initialize(field)
50
- @languages_range = import(field)
51
- end
36
+ # Digit a qvalue is padded with, up to three decimals.
37
+ DIGIT_ZERO = "0"
52
38
 
53
- # Finds the best matching language from available options based on user preferences.
54
- # Considers quality values and language tag specificity (e.g., "en-US" vs "en").
55
- #
56
- # @param available_langtags [Array<String, Symbol>] Languages supported by your application
57
- # @return [String, Symbol, nil] Best matching language tag or nil if no match found
39
+ # Error message raised when the field is neither a String nor +nil+.
40
+ FIELD_TYPE_ERROR = "Field must be a String or nil"
41
+
42
+ # An element made only of optional whitespace.
43
+ EMPTY = /\A[\x20\t]*\z/
44
+
45
+ # An element, in any letter case:
58
46
  #
59
- # @example Match against specific language options
60
- # parser.match("en", "fr", "de") # => "en" if English is preferred
61
- # @example Match with region-specific tags
62
- # parser.match("en-US", "en-GB", "fr") # => "en-GB" if British English is preferred
63
- def match(*available_langtags)
64
- Matcher.new(**languages_range).call(*available_langtags)
65
- end
47
+ # element = OWS language-range [ OWS ";" OWS "q=" qvalue ] OWS
48
+ # language-range = (1*8ALPHA *("-" 1*8alphanum)) / "*"
49
+ # qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
50
+ # OWS = *( SP / HTAB )
51
+ ELEMENT = /
52
+ \A [\x20\t]*
53
+ (?<range> \* | [A-Za-z]{1,8} (?: - [A-Za-z0-9]{1,8} )* )
54
+ (?: [\x20\t]* ; [\x20\t]* [Qq]= (?<qvalue> 0 (?: \. [0-9]{0,3} )? | 1 (?: \. 0{0,3} )? ) )?
55
+ [\x20\t]* \z
56
+ /x
57
+
58
+ class << self
59
+ # @param field [String, nil] the Accept-Language field value
60
+ # @return [Hash{String => Array(Integer, Integer)}] the ranges of the
61
+ # field, each of them unique
62
+ # @raise [TypeError] if +field+ is neither a String nor +nil+
63
+ #
64
+ # @example
65
+ # Parser.parse("da, en-GB;q=0.8, en;q=0.7")
66
+ # # => {"da" => [1000, 0], "en-gb" => [800, 1], "en" => [700, 2]}
67
+ def parse(field)
68
+ raise ::TypeError, FIELD_TYPE_ERROR unless field.nil? || field.is_a?(::String)
66
69
 
67
- private
70
+ elements(field).each_with_index.with_object({}) do |(element, position), ranges|
71
+ range, qvalue = ELEMENT.match(element)&.captures
72
+ next if range.nil?
68
73
 
69
- def import(field)
70
- "#{field}".downcase.delete(SPACE).split(SEPARATOR).inject({}) do |hash, lang|
71
- tag, quality = lang.split(SUFFIX)
72
- next hash unless valid_tag?(tag)
74
+ # Case conversion only ever sees a validated range: ASCII letters,
75
+ # digits and hyphens, never the raw bytes sent by the client.
76
+ weight = [quality(qvalue), position]
77
+ ranges.merge!(range.downcase(:ascii) => weight) { |_range, current, candidate| retain(current, candidate) }
78
+ end
79
+ end
80
+
81
+ private
73
82
 
74
- quality = DEFAULT_QUALITY if quality.nil?
75
- next hash unless valid_quality?(quality)
83
+ # The elements of a field that are considered. The field is copied as
84
+ # bytes, so that text in a broken encoding cannot raise.
85
+ def elements(field)
86
+ return [] if field.nil? || field.bytesize > MAX_FIELD_BYTES
76
87
 
77
- hash.merge(tag => BigDecimal(quality))
88
+ field.b.split(SEPARATOR).grep_v(EMPTY).first(MAX_ELEMENTS)
78
89
  end
79
- end
80
90
 
81
- def valid_quality?(quality)
82
- quality.match?(QVALUE_PATTERN)
83
- end
91
+ # A validated qvalue as an Integer from 0 to 1000: "0.85" gives 850.
92
+ def quality(qvalue)
93
+ return DEFAULT_QUALITY if qvalue.nil?
94
+
95
+ qvalue.delete(DOT).ljust(4, DIGIT_ZERO).to_i
96
+ end
84
97
 
85
- def valid_tag?(tag)
86
- return false if tag.nil?
98
+ # The occurrence retained for a range listed more than once: an
99
+ # exclusion (quality 0) if there is one, otherwise the highest quality,
100
+ # at its earliest position.
101
+ def retain(current, candidate)
102
+ return current if current.first.zero?
103
+ return candidate if candidate.first.zero?
87
104
 
88
- tag.match?(LANGTAG_PATTERN)
105
+ candidate.first > current.first ? candidate : current
106
+ end
89
107
  end
90
108
  end
91
109
  end
92
-
93
- require_relative "matcher"
@@ -1,30 +1,108 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # AcceptLanguage is a lightweight library for parsing Accept-Language HTTP headers
4
- # as defined in RFC 2616. It determines user language preferences and matches them
5
- # against your application's supported languages.
3
+ require_relative "accept_language/matcher"
4
+ require_relative "accept_language/parser"
5
+
6
+ # Negotiates a language from the +Accept-Language+ HTTP header field
7
+ # ({RFC 9110 Section 12.5.4}[https://www.rfc-editor.org/rfc/rfc9110#section-12.5.4]).
8
+ #
9
+ # {AcceptLanguage.negotiate} takes the value of the header and the languages
10
+ # your application supports, and returns the supported language the user
11
+ # prefers:
6
12
  #
7
- # @example Basic usage
8
- # AcceptLanguage.parse("da, en-GB;q=0.8, en;q=0.7").match(:en, :da)
13
+ # AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %i[en da])
9
14
  # # => :da
10
15
  #
11
- # @example With regional variants
12
- # AcceptLanguage.parse("fr-CH, fr;q=0.9").match(:fr, :"fr-CH")
13
- # # => :"fr-CH"
16
+ # AcceptLanguage.negotiate("da, en-GB;q=0.8, en;q=0.7", %w[en fr])
17
+ # # => "en"
18
+ #
19
+ # AcceptLanguage.negotiate("ja, zh;q=0.9", %i[en fr])
20
+ # # => nil
21
+ #
22
+ # The library has no dependencies, keeps no state, and never turns a part of
23
+ # the header into a Symbol. It is safe to call from any thread.
24
+ #
25
+ # == Rules
26
+ #
27
+ # [Matching]
28
+ # A language range matches a tag it equals, or that it prefixes at a
29
+ # hyphen: +en+ matches +en+ and +en-US+, not +eng+ (Basic Filtering,
30
+ # {RFC 4647 Section 3.3.1}[https://www.rfc-editor.org/rfc/rfc4647#section-3.3.1]).
31
+ # The comparison ignores case. <tt>*</tt> matches every tag.
32
+ # [Quality]
33
+ # When several ranges match a tag, the longest one decides its quality
34
+ # value, so that a specific range overrides a general one. <tt>*</tt> is the
35
+ # shortest range.
36
+ # [Exclusion]
37
+ # A tag with a quality of +0+, or that no range matches, is never returned.
38
+ # [Selection]
39
+ # The tag with the highest quality wins. Ties go to the range declared
40
+ # first in the header, then to the tag listed first in the available
41
+ # languages.
42
+ #
43
+ # For example:
44
+ #
45
+ # AcceptLanguage.negotiate("en-US, en;q=0", %i[en-GB en-US])
46
+ # # => :"en-US"
47
+ #
48
+ # AcceptLanguage.negotiate("*, en;q=0", %i[en fr])
49
+ # # => :fr
50
+ #
51
+ # AcceptLanguage.negotiate("fr;q=0.8, en;q=0.8", %i[en fr])
52
+ # # => :fr
53
+ #
54
+ # == Robustness
14
55
  #
15
- # @see https://tools.ietf.org/html/rfc2616#section-14.4
56
+ # The header is sent by the client, so it is handled as untrusted bytes:
57
+ #
58
+ # - an element that does not follow the grammar (an invalid range, an invalid
59
+ # quality value, whitespace where none is allowed) is ignored, and the rest
60
+ # of the header is still used;
61
+ # - a header longer than 4096 bytes is treated as absent;
62
+ # - only the first 50 elements of a header are considered.
63
+ #
64
+ # The complete behavior, including repeated ranges and the exact tie-breaking
65
+ # rule, is defined in the
66
+ # {specification}[https://github.com/cyril/accept_language.rb/blob/main/SPECIFICATION.md]
67
+ # shared with the
68
+ # {Elixir implementation}[https://github.com/cyril/accept_language.ex].
16
69
  module AcceptLanguage
17
- # Parses an Accept-Language header field value.
70
+ private_constant :Matcher, :Parser
71
+
72
+ # Returns the element of +available_langtags+ that best matches the
73
+ # +Accept-Language+ header value +field+, or +nil+ when none is acceptable.
74
+ #
75
+ # The arguments are checked on every call, including when +field+ is +nil+,
76
+ # so that a misuse shows up on the first request.
77
+ #
78
+ # @param field [String, nil] the value of the header, or +nil+ when the
79
+ # request has none. With Rack, that is <tt>env["HTTP_ACCEPT_LANGUAGE"]</tt>.
80
+ # @param available_langtags [Array<Symbol, String>] the languages the
81
+ # application supports, such as +I18n.available_locales+
18
82
  #
19
- # @param field [String] The Accept-Language header field value
20
- # @return [Parser] A parser object that responds to {Parser#match}
83
+ # @return [Symbol, String, nil] one of the elements of +available_langtags+,
84
+ # exactly as given, or +nil+
21
85
  #
22
- # @example
23
- # parser = AcceptLanguage.parse("en-GB, en;q=0.9")
24
- # parser.match(:en, :"en-GB") # => :"en-GB"
25
- def self.parse(field)
26
- Parser.new(field)
86
+ # @raise [TypeError] if +field+ is neither a String nor +nil+
87
+ # @raise [TypeError] if +available_langtags+ is not an Array of Symbols or
88
+ # Strings
89
+ #
90
+ # @example The result keeps the case of the available tag
91
+ # AcceptLanguage.negotiate("EN-gb", %i[en-GB fr])
92
+ # # => :"en-GB"
93
+ #
94
+ # @example A specific range is preferred to a general one
95
+ # AcceptLanguage.negotiate("fr-CH, fr;q=0.9", %i[fr fr-CH])
96
+ # # => :"fr-CH"
97
+ #
98
+ # @example The wildcard matches any other language
99
+ # AcceptLanguage.negotiate("de, *;q=0.5", %i[ja])
100
+ # # => :ja
101
+ #
102
+ # @example Falling back to a default language
103
+ # AcceptLanguage.negotiate(nil, %i[en fr]) || :en
104
+ # # => :en
105
+ def self.negotiate(field, available_langtags)
106
+ Matcher.call(Parser.parse(field), available_langtags)
27
107
  end
28
108
  end
29
-
30
- require_relative File.join("accept_language", "parser")
metadata CHANGED
@@ -1,31 +1,17 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: accept_language
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.1
4
+ version: 3.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Cyril Kato
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-01-19 00:00:00.000000000 Z
12
- dependencies:
13
- - !ruby/object:Gem::Dependency
14
- name: bigdecimal
15
- requirement: !ruby/object:Gem::Requirement
16
- requirements:
17
- - - ">="
18
- - !ruby/object:Gem::Version
19
- version: '0'
20
- type: :runtime
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - ">="
25
- - !ruby/object:Gem::Version
26
- version: '0'
27
- description: Parses the Accept-Language header from an HTTP request and produces a
28
- hash of languages and qualities.
11
+ date: 2026-12-03 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: A lightweight, thread-safe Ruby library for parsing the Accept-Language
14
+ HTTP header as defined in RFC 9110, with full support for BCP 47 language tags.
29
15
  email: contact@cyril.email
30
16
  executables: []
31
17
  extensions: []
@@ -41,6 +27,11 @@ licenses:
41
27
  - MIT
42
28
  metadata:
43
29
  rubygems_mfa_required: 'true'
30
+ source_code_uri: https://github.com/cyril/accept_language.rb
31
+ documentation_uri: https://rubydoc.info/github/cyril/accept_language.rb/main
32
+ bug_tracker_uri: https://github.com/cyril/accept_language.rb/issues
33
+ changelog_uri: https://github.com/cyril/accept_language.rb/blob/main/CHANGELOG.md
34
+ wiki_uri: https://github.com/cyril/accept_language.rb/wiki
44
35
  post_install_message:
45
36
  rdoc_options: []
46
37
  require_paths:
@@ -49,15 +40,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
49
40
  requirements:
50
41
  - - ">="
51
42
  - !ruby/object:Gem::Version
52
- version: 3.2.0
43
+ version: 3.3.0
53
44
  required_rubygems_version: !ruby/object:Gem::Requirement
54
45
  requirements:
55
46
  - - ">="
56
47
  - !ruby/object:Gem::Version
57
48
  version: '0'
58
49
  requirements: []
59
- rubygems_version: 3.4.19
50
+ rubygems_version: 3.5.22
60
51
  signing_key:
61
52
  specification_version: 4
62
- summary: "Parser for Accept-Language request HTTP header \U0001F310"
53
+ summary: Parser for Accept-Language request HTTP header
63
54
  test_files: []