roda-locale_kit 1.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 +7 -0
- data/CHANGELOG.md +11 -0
- data/EXAMPLES.md +213 -0
- data/LICENSE +21 -0
- data/README.md +312 -0
- data/lib/locale_kit/configuration.rb +130 -0
- data/lib/locale_kit/country_languages.rb +30 -0
- data/lib/locale_kit/detector.rb +108 -0
- data/lib/locale_kit/helpers.rb +64 -0
- data/lib/locale_kit/middleware.rb +89 -0
- data/lib/locale_kit/version.rb +5 -0
- data/lib/locale_kit.rb +86 -0
- data/lib/roda/plugins/locale_kit.rb +101 -0
- data/lib/roda-locale_kit.rb +4 -0
- metadata +235 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: b2e5ac0926193ae2b26380ad714bbe53a39dd2cc22d6ca4afa9c038dfbcebdb7
|
|
4
|
+
data.tar.gz: fb11ee09d0366a536df02e447fce552f0d1023c181721cd6b11f4f4e2049005b
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 102de58427ba05ed53d4c85c25d11b1c6dbe0e599571d63f7659e481f2f58b0500004e1334d6353707a6dd5c733bf2cebcb25730ce065aeac51b1d87541bc253
|
|
7
|
+
data.tar.gz: 3e05be9822808d528e32563fe785c54494f3fb6574265f955d8cbd096b1064b040902d9eb5d4fcc5f16225f14c34ca35048c0e60615c796b0e9d4323f63dcb9b
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to roda-locale_kit. Format roughly follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses
|
|
5
|
+
SemVer per [SemVer 2.0](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [1.0.0] - 2026-12-03
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Initial release, see the README for what the gem does
|
data/EXAMPLES.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# LocaleKit Examples
|
|
2
|
+
|
|
3
|
+
## Minimal English-Swedish setup
|
|
4
|
+
|
|
5
|
+
```ruby
|
|
6
|
+
# config/init/locale_kit.rb
|
|
7
|
+
LocaleKit.configure do |c|
|
|
8
|
+
c.available_locales = %i[en sv]
|
|
9
|
+
c.default_locale = :en
|
|
10
|
+
end
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
# app.rb
|
|
15
|
+
class App < Roda
|
|
16
|
+
plugin :locale_kit
|
|
17
|
+
|
|
18
|
+
route do |r|
|
|
19
|
+
r.hash_branches
|
|
20
|
+
|
|
21
|
+
r.root { I18n.t('greeting') }
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Visit `/`, get redirected to `/en` or `/sv` based on your browser language.
|
|
27
|
+
|
|
28
|
+
## With user preference resolver
|
|
29
|
+
|
|
30
|
+
```ruby
|
|
31
|
+
LocaleKit.configure do |c|
|
|
32
|
+
c.available_locales = %i[en sv de fr]
|
|
33
|
+
c.default_locale = :en
|
|
34
|
+
|
|
35
|
+
# Plug in however your app finds the current user from the Rack env.
|
|
36
|
+
c.current_user_resolver do |env|
|
|
37
|
+
user_id = env['rack.session'] && env['rack.session'][:user_id]
|
|
38
|
+
user_id && User[user_id]
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
c.user_locale_resolver do |user|
|
|
42
|
+
user.respond_to?(:preferred_locale) ? user.preferred_locale : nil
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Make sure your User model has a `preferred_locale` column. Update it from a settings page:
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
r.post 'settings/locale' do
|
|
51
|
+
current_user.update(preferred_locale: r.params['locale'])
|
|
52
|
+
set_user_locale(r.params['locale'])
|
|
53
|
+
r.redirect settings_path
|
|
54
|
+
end
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## With MaxMind GeoLite2
|
|
58
|
+
|
|
59
|
+
```ruby
|
|
60
|
+
require 'maxmind/db'
|
|
61
|
+
|
|
62
|
+
GEO_DB = MaxMind::DB.new(
|
|
63
|
+
File.expand_path('data/GeoLite2-Country.mmdb', __dir__),
|
|
64
|
+
mode: MaxMind::DB::MODE_MEMORY
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
LocaleKit.configure do |c|
|
|
68
|
+
c.available_locales = %i[en sv de fr es it]
|
|
69
|
+
c.default_locale = :en
|
|
70
|
+
|
|
71
|
+
c.geo_resolver do |ip|
|
|
72
|
+
record = GEO_DB.get(ip)
|
|
73
|
+
record&.dig('country', 'iso_code')
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The block receives the request IP and returns a 2-letter country code (or nil). LocaleKit's built-in country-to-language map handles the rest.
|
|
79
|
+
|
|
80
|
+
## With ip-api.com (no local database)
|
|
81
|
+
|
|
82
|
+
```ruby
|
|
83
|
+
require 'net/http'
|
|
84
|
+
require 'json'
|
|
85
|
+
|
|
86
|
+
LocaleKit.configure do |c|
|
|
87
|
+
c.available_locales = %i[en sv]
|
|
88
|
+
c.default_locale = :en
|
|
89
|
+
|
|
90
|
+
c.geo_resolver do |ip|
|
|
91
|
+
next nil if ip == '127.0.0.1' || ip.start_with?('192.168.', '10.')
|
|
92
|
+
|
|
93
|
+
uri = URI("http://ip-api.com/json/#{ip}?fields=countryCode")
|
|
94
|
+
response = Net::HTTP.get_response(uri)
|
|
95
|
+
next nil unless response.is_a?(Net::HTTPSuccess)
|
|
96
|
+
|
|
97
|
+
JSON.parse(response.body)['countryCode']
|
|
98
|
+
rescue StandardError
|
|
99
|
+
nil
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
For production, cache the result. ip-api.com has rate limits and adds latency to every first-time visitor.
|
|
105
|
+
|
|
106
|
+
## Custom country to language mapping
|
|
107
|
+
|
|
108
|
+
The default map picks one primary language per country. Override for multilingual countries or custom needs:
|
|
109
|
+
|
|
110
|
+
```ruby
|
|
111
|
+
LocaleKit.configure do |c|
|
|
112
|
+
c.available_locales = %i[en fr nl de]
|
|
113
|
+
|
|
114
|
+
# Belgium has three official languages. Default to French.
|
|
115
|
+
# Switzerland too. Default to German.
|
|
116
|
+
c.country_language_map = LocaleKit::COUNTRY_LANGUAGES.merge(
|
|
117
|
+
'BE' => :fr,
|
|
118
|
+
'CH' => :de,
|
|
119
|
+
'LU' => :fr
|
|
120
|
+
)
|
|
121
|
+
end
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## hreflang tags for SEO
|
|
125
|
+
|
|
126
|
+
```erb
|
|
127
|
+
<head>
|
|
128
|
+
<% available_locales.each do |loc| %>
|
|
129
|
+
<link rel="alternate" hreflang="<%= loc %>" href="<%= request.scheme %>://<%= request.host %><%= path_with_locale(loc) %>">
|
|
130
|
+
<% end %>
|
|
131
|
+
<link rel="alternate" hreflang="x-default" href="<%= request.scheme %>://<%= request.host %><%= path_with_locale(LocaleKit.configuration.default_locale) %>">
|
|
132
|
+
</head>
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Tells search engines which URL serves which language for the same content.
|
|
136
|
+
|
|
137
|
+
## Login route setting locale
|
|
138
|
+
|
|
139
|
+
```ruby
|
|
140
|
+
r.post 'login' do
|
|
141
|
+
user = User.authenticate(r.params['email'], r.params['password'])
|
|
142
|
+
|
|
143
|
+
if user
|
|
144
|
+
session[:user_id] = user.id
|
|
145
|
+
|
|
146
|
+
if user.preferred_locale && LocaleKit.configuration.supports?(user.preferred_locale.to_sym)
|
|
147
|
+
set_user_locale(user.preferred_locale)
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
r.redirect dashboard_path # auto-localized via the path plugin override
|
|
151
|
+
else
|
|
152
|
+
flash[:error] = I18n.t('login.failed')
|
|
153
|
+
r.redirect login_path
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Excluding API paths
|
|
159
|
+
|
|
160
|
+
If your app serves both HTML and a JSON API, exclude the API:
|
|
161
|
+
|
|
162
|
+
```ruby
|
|
163
|
+
LocaleKit.configure do |c|
|
|
164
|
+
c.available_locales = %i[en sv]
|
|
165
|
+
c.excluded_paths = ['/assets', '/api', '/webhooks', '/health', '/favicon.ico']
|
|
166
|
+
end
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
API clients send `Accept: application/json` and would not benefit from a locale redirect anyway. The middleware also skips redirects for non-HTML requests as a safety net.
|
|
170
|
+
|
|
171
|
+
You can mix string prefixes and regular expressions:
|
|
172
|
+
|
|
173
|
+
```ruby
|
|
174
|
+
c.excluded_paths = ['/assets', %r{\.(?:json|xml)\z}]
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Custom switcher
|
|
178
|
+
|
|
179
|
+
The HTML in the README is just a starting point. Build it however fits your layout:
|
|
180
|
+
|
|
181
|
+
```erb
|
|
182
|
+
<div class="lang-picker">
|
|
183
|
+
<% available_locales.each do |loc| %>
|
|
184
|
+
<% if loc == current_locale %>
|
|
185
|
+
<span class="active"><%= loc.to_s.upcase %></span>
|
|
186
|
+
<% else %>
|
|
187
|
+
<a href="<%= path_with_locale(loc) %>" rel="nofollow">
|
|
188
|
+
<%= loc.to_s.upcase %>
|
|
189
|
+
</a>
|
|
190
|
+
<% end %>
|
|
191
|
+
<% end %>
|
|
192
|
+
</div>
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Note: this version uses GET links, which means the cookie does not get set. The user keeps the new locale only because the URL prefix takes precedence. To persist across pages without a URL prefix (e.g. after a form submission redirects somewhere else), use the POST form switcher from the README instead.
|
|
196
|
+
|
|
197
|
+
## Testing locale detection in isolation
|
|
198
|
+
|
|
199
|
+
```ruby
|
|
200
|
+
require 'locale_kit'
|
|
201
|
+
require 'rack/mock'
|
|
202
|
+
|
|
203
|
+
LocaleKit.configure do |c|
|
|
204
|
+
c.available_locales = %i[en sv de]
|
|
205
|
+
c.default_locale = :en
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
env = Rack::MockRequest.env_for('/', 'HTTP_ACCEPT_LANGUAGE' => 'sv-SE,sv;q=0.9,en;q=0.8')
|
|
209
|
+
request = Rack::Request.new(env)
|
|
210
|
+
|
|
211
|
+
LocaleKit.detect(request)
|
|
212
|
+
# => :sv
|
|
213
|
+
```
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marcel Asio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
# LocaleKit
|
|
2
|
+
|
|
3
|
+
A Roda plugin (and Rack middleware) for URL-prefix locale handling with a detection cascade.
|
|
4
|
+
|
|
5
|
+
LocaleKit lets you serve a multilingual site under `/sv/`, `/en/`, `/de/` style URLs without putting the locale in any of your route definitions. The middleware strips the prefix before Roda's router runs, and the `path` helpers add it back when generating links.
|
|
6
|
+
|
|
7
|
+
- [Features](#features)
|
|
8
|
+
- [Installation](#installation)
|
|
9
|
+
- [Configuration](#configuration)
|
|
10
|
+
- [Configuration reference](#configuration-reference)
|
|
11
|
+
- [How requests flow](#how-requests-flow)
|
|
12
|
+
- [Detection order](#detection-order)
|
|
13
|
+
- [Routes stay clean](#routes-stay-clean)
|
|
14
|
+
- [Generating links](#generating-links)
|
|
15
|
+
- [What the middleware sets](#what-the-middleware-sets)
|
|
16
|
+
- [Switching language](#switching-language)
|
|
17
|
+
- [Login flow](#login-flow)
|
|
18
|
+
- [Excluded paths](#excluded-paths)
|
|
19
|
+
- [Custom detection chain](#custom-detection-chain)
|
|
20
|
+
- [Standalone Rack apps](#standalone-rack-apps)
|
|
21
|
+
- [What LocaleKit does not do](#what-locale-kit-does-not-do)
|
|
22
|
+
- [More examples](#more-examples)
|
|
23
|
+
- [License](#license)
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
- URL prefix routing: `/sv/about`, `/en/about`. Routes stay locale-agnostic.
|
|
28
|
+
- Detection cascade: user preference, cookie, Accept-Language header, IP geolocation, default.
|
|
29
|
+
- Pluggable user resolver and geo resolver. No hard dependency on a specific auth library or geo backend.
|
|
30
|
+
- Wraps Roda's `:path` plugin so generated path helpers (`*_path`) auto-localize, and `link_to` localizes String hrefs. The `url` helper inherits the prefix.
|
|
31
|
+
- Mounts a `POST /locale/:locale` switcher route via `hash_branches`.
|
|
32
|
+
- Country-to-language map covering EU and major markets, replaceable in config.
|
|
33
|
+
- Works behind reverse proxies and mounted apps — redirects respect `SCRIPT_NAME`.
|
|
34
|
+
- The middleware can be used standalone on any Rack app; the path-helper auto-localization is the Roda-specific bit.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```ruby
|
|
39
|
+
# Gemfile
|
|
40
|
+
gem 'roda-locale_kit'
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The gem name carries the `roda-` prefix; the library, require path, and plugin keep the `locale_kit` name.
|
|
44
|
+
|
|
45
|
+
```ruby
|
|
46
|
+
class App < Roda
|
|
47
|
+
plugin :locale_kit
|
|
48
|
+
end
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The plugin pulls in `:path`, `:hash_branches`, `:cookies`, and `:link_to` as dependencies. Loading the plugin twice on the same app is a no-op the second time.
|
|
52
|
+
|
|
53
|
+
## Configuration
|
|
54
|
+
|
|
55
|
+
```ruby
|
|
56
|
+
# config/init/locale_kit.rb (or wherever your initializers live)
|
|
57
|
+
LocaleKit.configure do |c|
|
|
58
|
+
c.available_locales = %i[en sv de]
|
|
59
|
+
c.default_locale = :en
|
|
60
|
+
c.cookie_name = '_my_app.locale'
|
|
61
|
+
|
|
62
|
+
# Resolve the current user from the Rack env. No default — plug in
|
|
63
|
+
# your auth scheme. Return any object (or nil); it is forwarded to
|
|
64
|
+
# user_locale_resolver below.
|
|
65
|
+
c.current_user_resolver do |env|
|
|
66
|
+
user_id = env['rack.session'] && env['rack.session'][:user_id]
|
|
67
|
+
user_id && User[user_id]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Resolve locale from the object returned by current_user_resolver.
|
|
71
|
+
# Return a symbol or string locale, or nil.
|
|
72
|
+
c.user_locale_resolver do |user|
|
|
73
|
+
user.preferred_locale if user.respond_to?(:preferred_locale)
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Resolve country code from an IP. Return a 2-letter ISO code or nil.
|
|
77
|
+
# No default backend. Plug in MaxMind, ip-api, or any other service.
|
|
78
|
+
c.geo_resolver do |ip|
|
|
79
|
+
record = MAXMIND_DB.get(ip)
|
|
80
|
+
record&.dig('country', 'iso_code')
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`LocaleKit.configure` can be called more than once; later blocks add to or override the same configuration object. Treat it as boot-time setup — don't change values per request.
|
|
86
|
+
|
|
87
|
+
## Configuration reference
|
|
88
|
+
|
|
89
|
+
| Attribute | Type | Default | Notes |
|
|
90
|
+
| --- | --- | --- | --- |
|
|
91
|
+
| `available_locales` | Array of Symbols | `[:en]` | Setter coerces strings to symbols and adds them to `I18n.available_locales` (union), so `I18n.locale =` never raises for a locale LocaleKit supports. |
|
|
92
|
+
| `default_locale` | Symbol | `:en` | Final fallback in the cascade. |
|
|
93
|
+
| `cookie_name` | String | `'locale'` | Set the cookie name to something app-specific in production. |
|
|
94
|
+
| `cookie_max_age` | Integer (seconds) | 1 year | Used when `set_user_locale` writes the cookie. |
|
|
95
|
+
| `excluded_paths` | Array of String / Regexp | see below | Bypass locale handling entirely. String entries are prefix matches; Regexp entries are matched against the full path. |
|
|
96
|
+
| `detect_on_excluded_paths` | Boolean | `true` | Run the detection cascade on excluded paths so `I18n.locale` is set there too. Set to `false` to skip detection (and the resolver calls it makes) on static/API paths. |
|
|
97
|
+
| `country_language_map` | Hash | `LocaleKit::COUNTRY_LANGUAGES` | ISO-3166-1 alpha-2 → language symbol. Used by the geo step. |
|
|
98
|
+
| `current_user_resolver` | Proc (block) | `nil` | Receives Rack `env`, returns any object (or `nil`). |
|
|
99
|
+
| `user_locale_resolver` | Proc (block) | `nil` | Receives the object from `current_user_resolver`, returns a locale or `nil`. Errors are swallowed. |
|
|
100
|
+
| `geo_resolver` | Proc (block) | `nil` | Receives the request IP, returns an ISO country code (string) or `nil`. Errors are swallowed. |
|
|
101
|
+
|
|
102
|
+
Default `excluded_paths`: `/assets`, `/api`, `/favicon.ico`, `/robots.txt`, `/sitemap.xml`.
|
|
103
|
+
|
|
104
|
+
## How requests flow
|
|
105
|
+
|
|
106
|
+
1. Browser requests `/about`.
|
|
107
|
+
2. Middleware sees no locale prefix. Runs the detection cascade.
|
|
108
|
+
3. Detected locale is `:sv`. Middleware redirects (302) to `/sv/about`.
|
|
109
|
+
4. Browser requests `/sv/about`.
|
|
110
|
+
5. Middleware extracts `:sv`, sets `I18n.locale = :sv` and `env['locale_kit.locale'] = :sv`, rewrites `PATH_INFO` to `/about`.
|
|
111
|
+
6. Roda's router matches `r.is 'about'` as if no prefix existed.
|
|
112
|
+
7. View renders. The `path` helpers prepend `/sv/` to all generated links.
|
|
113
|
+
|
|
114
|
+
Non-HTML requests (JSON, etc.) are not redirected — the middleware sets the locale in place and passes the request through with `PATH_INFO` intact.
|
|
115
|
+
|
|
116
|
+
## Detection order
|
|
117
|
+
|
|
118
|
+
1. **User preference**. If a user is logged in and the resolver returns a supported locale, use it.
|
|
119
|
+
2. **Cookie**. If the user has explicitly chosen a language before, use the saved cookie value.
|
|
120
|
+
3. **Accept-Language header**. Pick the highest-ranked supported language. Tries exact match first (`en-US`), then base language (`en`).
|
|
121
|
+
4. **IP geolocation**. If a geo resolver is configured, look up the country and map to a primary language via `country_language_map`.
|
|
122
|
+
5. **Default**. The locale set in `default_locale`.
|
|
123
|
+
|
|
124
|
+
A resolver block that raises is treated as "no result" — the step returns `nil` and the cascade moves on. This applies to `user_locale_resolver` and `geo_resolver` (cookie and Accept-Language don't run user code, so they don't need the safety net).
|
|
125
|
+
|
|
126
|
+
## Routes stay clean
|
|
127
|
+
|
|
128
|
+
```ruby
|
|
129
|
+
class App < Roda
|
|
130
|
+
plugin :locale_kit
|
|
131
|
+
|
|
132
|
+
path :about, '/about-us'
|
|
133
|
+
path User do |u|
|
|
134
|
+
"/users/#{u.id}"
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
route do |r|
|
|
138
|
+
r.hash_branches # mounts /locale/:loc for the switcher
|
|
139
|
+
|
|
140
|
+
r.root { 'Hello' }
|
|
141
|
+
r.is 'about-us' do
|
|
142
|
+
view('about')
|
|
143
|
+
end
|
|
144
|
+
r.is 'users', Integer do |id|
|
|
145
|
+
user = User[id]
|
|
146
|
+
"Profile for #{user.name}, link: #{path(user)}"
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
No `/sv/` or `/en/` in any of these. The middleware strips the prefix on the way in, and the helpers prepend it on the way out.
|
|
153
|
+
|
|
154
|
+
## Generating links
|
|
155
|
+
|
|
156
|
+
```erb
|
|
157
|
+
<%= about_path %> <%# /sv/about-us when current locale is :sv %>
|
|
158
|
+
<%= path(@user) %> <%# /sv/users/42 via object dispatch %>
|
|
159
|
+
<%= localized_url('/cart') %> <%# /sv/cart explicit helper for arbitrary paths %>
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`localized_url` strips any existing locale prefix before adding a new one, so passing an already-localized path is safe:
|
|
163
|
+
|
|
164
|
+
```ruby
|
|
165
|
+
localized_url('/en/cart', locale: :sv) # => "/sv/cart"
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
The following pass through unchanged (no prefix added):
|
|
169
|
+
|
|
170
|
+
- URLs with any URI scheme (`http://`, `https://`, `mailto:`, `tel:`, `sms:`, …) and protocol-relative `//host` URLs.
|
|
171
|
+
- Paths matching `excluded_paths`.
|
|
172
|
+
|
|
173
|
+
For explicit cross-locale links (e.g. hreflang tags or a custom switcher):
|
|
174
|
+
|
|
175
|
+
```erb
|
|
176
|
+
<link rel="alternate" hreflang="sv" href="<%= path_with_locale(:sv) %>">
|
|
177
|
+
<link rel="alternate" hreflang="en" href="<%= path_with_locale(:en) %>">
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## What the middleware sets
|
|
181
|
+
|
|
182
|
+
On every non-excluded request, the middleware sets two pieces of state:
|
|
183
|
+
|
|
184
|
+
- `request.env['locale_kit.locale']` — Symbol. Read this from any downstream middleware or framework that needs the active locale.
|
|
185
|
+
- `I18n.locale` — same value, always set; `i18n` is a hard runtime dependency and the configured locales are added to `I18n.available_locales` automatically.
|
|
186
|
+
|
|
187
|
+
`PATH_INFO` is rewritten to remove the locale prefix before your routes see it.
|
|
188
|
+
|
|
189
|
+
For requests that match `excluded_paths`, the locale is still detected and applied to `env['locale_kit.locale']` and `I18n.locale`, but `PATH_INFO` is left untouched and no redirect is issued. If nothing on those paths is locale-dependent, set `detect_on_excluded_paths = false` to skip detection there entirely — this avoids calling `current_user_resolver` (and potentially `geo_resolver`) on every asset request, and leaves `env['locale_kit.locale']` unset on those paths.
|
|
190
|
+
|
|
191
|
+
## Switching language
|
|
192
|
+
|
|
193
|
+
The plugin mounts a `POST /locale/:locale` switcher via `hash_branches`. Drop this snippet into your layout — page structure varies per project, so we ship the HTML for you to adapt rather than a bundled partial:
|
|
194
|
+
|
|
195
|
+
```erb
|
|
196
|
+
<nav class="locale-switcher" aria-label="Language">
|
|
197
|
+
<ul>
|
|
198
|
+
<% available_locales.each do |loc| %>
|
|
199
|
+
<li>
|
|
200
|
+
<% if loc == current_locale %>
|
|
201
|
+
<strong><%= loc.to_s.upcase %></strong>
|
|
202
|
+
<% else %>
|
|
203
|
+
<form action="/locale/<%= loc %>" method="post" style="display:inline">
|
|
204
|
+
<%= csrf_tag if respond_to?(:csrf_tag) %>
|
|
205
|
+
<input type="hidden" name="return_to" value="<%= request.path_info %>">
|
|
206
|
+
<button type="submit"><%= loc.to_s.upcase %></button>
|
|
207
|
+
</form>
|
|
208
|
+
<% end %>
|
|
209
|
+
</li>
|
|
210
|
+
<% end %>
|
|
211
|
+
</ul>
|
|
212
|
+
</nav>
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
When Roda's `:route_csrf` plugin is loaded, the switcher route calls `check_csrf!`, so the `csrf_tag` in the form is required.
|
|
216
|
+
|
|
217
|
+
The route sets the cookie, then redirects to the same path under the new locale prefix. Posting to an unsupported locale returns a 404. `return_to` must be an app-relative path starting with `/`; absolute URLs or malformed values fall back to `/`, so the redirect can never leave your origin.
|
|
218
|
+
|
|
219
|
+
A GET-link version (see [EXAMPLES.md](EXAMPLES.md)) is simpler but does *not* set the cookie — the user keeps the new locale only as long as the URL prefix carries it.
|
|
220
|
+
|
|
221
|
+
## Login flow
|
|
222
|
+
|
|
223
|
+
When a user logs in, set their preferred locale immediately:
|
|
224
|
+
|
|
225
|
+
```ruby
|
|
226
|
+
r.post 'login' do
|
|
227
|
+
user = User.authenticate(r.params['email'], r.params['password'])
|
|
228
|
+
if user
|
|
229
|
+
session[:user_id] = user.id
|
|
230
|
+
set_user_locale(user.preferred_locale) if user.preferred_locale
|
|
231
|
+
r.redirect dashboard_path
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`set_user_locale` silently ignores unsupported values, so you can pass `user.preferred_locale` directly without an extra `supports?` check. It does *not* update `request.env['locale_kit.locale']` for the current request — that's already been decided by the time you hit the action.
|
|
237
|
+
|
|
238
|
+
## Excluded paths
|
|
239
|
+
|
|
240
|
+
By default these paths skip locale handling: `/assets`, `/api`, `/favicon.ico`, `/robots.txt`, `/sitemap.xml`. Override:
|
|
241
|
+
|
|
242
|
+
```ruby
|
|
243
|
+
LocaleKit.configure do |c|
|
|
244
|
+
c.excluded_paths = ['/assets', '/api', '/webhooks', '/health', %r{\.json\z}]
|
|
245
|
+
end
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
String entries are treated as path prefixes (trailing slash optional). Regexp entries are matched against the full path. API endpoints typically should not redirect, so list them here.
|
|
249
|
+
|
|
250
|
+
`localized_url` and the auto-localized `path` helpers leave excluded paths unchanged when generating links.
|
|
251
|
+
|
|
252
|
+
## Custom detection chain
|
|
253
|
+
|
|
254
|
+
The default cascade is exposed as `LocaleKit::Detector::DEFAULT_CHAIN` — an array of Symbols naming the built-in steps: `:user_preference`, `:cookie`, `:accept_language`, `:ip_geolocation`. Swap, reorder, or extend it by instantiating `Detector` with a custom `chain:`:
|
|
255
|
+
|
|
256
|
+
```ruby
|
|
257
|
+
subdomain = lambda do |request, _user, config|
|
|
258
|
+
candidate = request.host.split('.').first.to_sym
|
|
259
|
+
candidate if config.supports?(candidate)
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
chain = [subdomain, *LocaleKit::Detector::DEFAULT_CHAIN]
|
|
263
|
+
detector = LocaleKit::Detector.new(LocaleKit.configuration, chain: chain)
|
|
264
|
+
detector.detect(Rack::Request.new(env))
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
A custom step is anything responding to `call(request, user, config)`, returning a Symbol from `available_locales` or `nil` to fall through. The final `default_locale` fallback is built into `Detector#detect`, so it never needs a chain entry.
|
|
268
|
+
|
|
269
|
+
To replace the middleware's cascade globally, you currently need to wrap it — there is no per-process detection-chain hook on the middleware itself. PRs welcome.
|
|
270
|
+
|
|
271
|
+
## Standalone Rack apps
|
|
272
|
+
|
|
273
|
+
LocaleKit's middleware and helpers work without Roda. The auto-localized `path` helpers are Roda-specific, but everything else is just Rack:
|
|
274
|
+
|
|
275
|
+
```ruby
|
|
276
|
+
require 'locale_kit'
|
|
277
|
+
|
|
278
|
+
LocaleKit.configure do |c|
|
|
279
|
+
c.available_locales = %i[en sv]
|
|
280
|
+
c.default_locale = :en
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
class MyApp
|
|
284
|
+
include LocaleKit::Helpers # needs `request` and `response` in scope
|
|
285
|
+
|
|
286
|
+
def call(env)
|
|
287
|
+
# ...
|
|
288
|
+
end
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
use LocaleKit::Middleware
|
|
292
|
+
run MyApp.new
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
For frameworks that don't expose `request`/`response` the same way Roda does, call `LocaleKit.detect(Rack::Request.new(env))` directly and read `env['locale_kit.locale']` yourself.
|
|
296
|
+
|
|
297
|
+
## What LocaleKit does not do
|
|
298
|
+
|
|
299
|
+
- It does not translate strings. Use the `i18n` gem (or [roda-i18n](https://github.com/kematzy/roda-i18n)) for that.
|
|
300
|
+
- It does not store the user's preferred locale in the database. Your app does.
|
|
301
|
+
- It does not ship a geo backend. Plug in MaxMind GeoLite2, ip-api.com, or similar via `geo_resolver`.
|
|
302
|
+
- It does not handle subdomain or domain-based locales (`sv.example.com`, `example.se`). URL prefix only — although you can write a custom chain step for it (see [Custom detection chain](#custom-detection-chain)).
|
|
303
|
+
|
|
304
|
+
## More examples
|
|
305
|
+
|
|
306
|
+
See [EXAMPLES.md](EXAMPLES.md) for: MaxMind setup, ip-api.com integration, hreflang tags, custom country mappings, testing locale detection in isolation, and a few other recipes.
|
|
307
|
+
|
|
308
|
+
For the full API, see the generated RDoc — start at `LocaleKit`, `LocaleKit::Configuration`, and `Roda::RodaPlugins::LocaleKit`.
|
|
309
|
+
|
|
310
|
+
## License
|
|
311
|
+
|
|
312
|
+
MIT.
|