Method: AcceptLanguage.parse

Defined in:
lib/accept_language.rb

.parse(field) ⇒ Parser

Parses an Accept-Language header field value and returns a parser instance that can be used to match against available languages.

The parser handles all aspects of the Accept-Language specification:

  • Quality values (+q=0+ to q=1, default 1 when omitted)

  • Language range validation per RFC 4647 Section 2.1

  • Wildcards (+*+)

  • Case normalization (matching is case-insensitive)

Invalid language ranges or malformed quality values in the input are silently ignored, allowing the parser to handle real-world headers that may not strictly conform to specifications.

Examples:

Basic parsing and matching

parser = AcceptLanguage.parse("en-GB, en;q=0.9, fr;q=0.8")
parser.match(:en, :"en-GB", :fr)
# => :"en-GB"

Handling missing or empty headers

AcceptLanguage.parse("").match(:en, :fr)
# => nil

AcceptLanguage.parse(nil).match(:en, :fr)
# => nil

Reusing a parser instance

# Parse once, match multiple times
user_prefs = AcceptLanguage.parse(header_value)

# Match for UI language
ui_locale = user_prefs.match(*available_ui_locales)

# Match for content language
content_locale = user_prefs.match(*available_content_locales)

Handling edge cases

# Invalid q-values are ignored
AcceptLanguage.parse("en;q=2.0, fr;q=0.8").match(:en, :fr)
# => :fr  (en is ignored due to invalid q-value > 1)

# Invalid language ranges are ignored
AcceptLanguage.parse("123invalid, fr;q=0.8").match(:fr)
# => :fr

Parameters:

  • field (String, nil)

    the Accept-Language header field value. Typically obtained from request.headers[“HTTP_ACCEPT_LANGUAGE”] in Rails or env in Rack applications. When nil is passed (header absent), it is treated as an empty string, resulting in a parser that matches no languages.

Returns:

  • (Parser)

    a parser instance configured with the language preferences from the header. Call AcceptLanguage::Parser#match on this instance to find the best matching language from your available options.

Raises:

  • (TypeError)

    if field is neither a String nor nil

See Also:

Since:

  • 1.0.0



268
269
270
# File 'lib/accept_language.rb', line 268

def self.parse(field)
  Parser.new(field)
end