-
Notifications
You must be signed in to change notification settings - Fork 7
Getting Started
Cyril Kato edited this page Jan 20, 2026
·
1 revision
This guide will help you install AcceptLanguage and write your first language matching code in under 5 minutes.
Add the gem to your Gemfile:
gem "accept_language"Then run:
bundle installOr install it directly:
gem install accept_languageThe library has a simple two-step workflow: parse the header, then match against your available languages.
require "accept_language"
# Step 1: Parse the Accept-Language header
parser = AcceptLanguage.parse("fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7")
# Step 2: Match against your available languages
parser.match(:en, :fr, :de)
# => :frIn this example, the user prefers Swiss French (fr-CH), but since your app doesn't support it, the gem returns :fr (French) as the next best match.
You can chain the methods for a more concise syntax:
AcceptLanguage.parse("fr-CH, fr;q=0.9, en;q=0.8").match(:en, :fr, :"fr-CH")
# => :"fr-CH"The match method returns:
- A Symbol — the best matching language from your available options
- nil — if no acceptable match is found
# Match found
AcceptLanguage.parse("ja, en;q=0.8").match(:en, :fr)
# => :en
# No match found
AcceptLanguage.parse("ja, zh").match(:en, :fr)
# => nilWhen the Accept-Language header is absent or empty, the parser returns nil for any match:
AcceptLanguage.parse(nil).match(:en, :fr)
# => nil
AcceptLanguage.parse("").match(:en, :fr)
# => nilThis makes it easy to fall back to a default locale:
header = nil # or request.env["HTTP_ACCEPT_LANGUAGE"]
locale = AcceptLanguage.parse(header).match(:en, :fr, :de) || :en
locale
# => :en (your default)| Code | Result | Why |
|---|---|---|
AcceptLanguage.parse("en, fr;q=0.8").match(:en, :fr)
|
:en
|
English has higher quality (1.0 vs 0.8) |
AcceptLanguage.parse("en").match(:"en-US", :"en-GB")
|
:"en-US"
|
Prefix matching: en matches en-US
|
AcceptLanguage.parse("de, *;q=0.5").match(:ja)
|
:ja
|
Wildcard * matches any language
|
AcceptLanguage.parse("*, en;q=0").match(:en, :fr)
|
:fr
|
English is excluded (q=0)
|
AcceptLanguage.parse("ja").match(:en, :fr)
|
nil
|
No match available |
Now that you have the basics, explore the core concepts:
- Understanding Quality Values — Learn how quality values affect language selection
- Basic Filtering Explained — Understand prefix matching rules
- Working with Wildcards — Accept any language as a fallback
- Excluding Languages — Explicitly reject specific languages
- Rails Integration Guide — Set up automatic locale detection in Rails
- Rack Integration Guide — Build middleware for Sinatra, Hanami, or pure Rack