Module: AcceptLanguage

Defined in:
lib/accept_language.rb,
lib/accept_language/parser.rb,
lib/accept_language/matcher.rb

Overview

AcceptLanguage is a lightweight library that parses Accept-Language HTTP headers (RFC 2616) to determine user language preferences. It converts raw header values into a structured format for matching against your application’s supported languages.

Examples:

AcceptLanguage.parse("da, en-GB;q=0.8, en;q=0.7")
# => #<AcceptLanguage::Parser:0x00007 @languages_range={"da"=>1.0, "en-GB"=>0.8, "en"=>0.7}>

Integration with Rails

class ApplicationController < ActionController::Base
  before_action :set_locale

  private

  def set_locale
    header = request.env["HTTP_ACCEPT_LANGUAGE"]
    locale = AcceptLanguage.parse(header).match(*I18n.available_locales)
    I18n.locale = locale || I18n.default_locale
  end
end

See Also:

Defined Under Namespace

Classes: Matcher, Parser

Class Method Summary collapse

Class Method Details

.parse(field) ⇒ Parser

Parses an Accept-Language header field value into a Parser object, which can then be used to match user’s preferred languages against the languages your application supports. This method accepts a string argument in the format as described in RFC 2616 Section 14.4, and returns a Parser object which responds to the #match method.

Examples:

AcceptLanguage.parse("da, en-GB;q=0.8, en;q=0.7")
# => #<AcceptLanguage::Parser:0x00007 @languages_range={"da"=>1.0, "en-GB"=>0.8, "en"=>0.7}>

Parameters:

  • field (String)

    the Accept-Language header field value.

Returns:

  • (Parser)

    a Parser object that responds to #match method.



38
39
40
# File 'lib/accept_language.rb', line 38

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