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
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'logger'
|
|
4
|
+
|
|
5
|
+
module LocaleKit
|
|
6
|
+
# Configuration container, accessed via LocaleKit.configure. One instance
|
|
7
|
+
# per process; set values at boot and treat as immutable afterwards. See
|
|
8
|
+
# the README's configuration reference for the attribute guide.
|
|
9
|
+
class Configuration
|
|
10
|
+
# Supported locale Symbols. See available_locales=.
|
|
11
|
+
attr_reader :available_locales
|
|
12
|
+
|
|
13
|
+
# Final fallback locale Symbol in the detection cascade.
|
|
14
|
+
attr_reader :default_locale
|
|
15
|
+
|
|
16
|
+
# Name of the locale-preference cookie. Default: <tt>'locale'</tt>.
|
|
17
|
+
attr_accessor :cookie_name
|
|
18
|
+
|
|
19
|
+
# Cookie +Max-Age+ in seconds. Default: one year.
|
|
20
|
+
attr_accessor :cookie_max_age
|
|
21
|
+
|
|
22
|
+
# String and/or Regexp entries that bypass locale handling.
|
|
23
|
+
# See LocaleKit.excluded_path? for match semantics.
|
|
24
|
+
attr_reader :excluded_paths
|
|
25
|
+
|
|
26
|
+
# Whether the middleware runs detection on excluded paths (default
|
|
27
|
+
# +true+). Set +false+ to skip it — avoids resolver calls on every
|
|
28
|
+
# static asset when nothing rendered there is locale-dependent.
|
|
29
|
+
attr_accessor :detect_on_excluded_paths
|
|
30
|
+
|
|
31
|
+
# Precompiled exclusions used by LocaleKit.excluded_path?: exact
|
|
32
|
+
# prefixes (trailing slash chomped), the same with a slash appended,
|
|
33
|
+
# and the Regexp entries.
|
|
34
|
+
attr_reader :excluded_path_prefixes
|
|
35
|
+
attr_reader :excluded_path_prefix_slashes, :excluded_path_regexps
|
|
36
|
+
|
|
37
|
+
# Precompiled locale-prefix triples used by LocaleKit.split_locale_prefix.
|
|
38
|
+
attr_reader :locale_path_prefixes
|
|
39
|
+
|
|
40
|
+
# ISO 3166-1 alpha-2 country code (uppercase String) → language Symbol,
|
|
41
|
+
# used by the geo step. Default: LocaleKit::COUNTRY_LANGUAGES.
|
|
42
|
+
attr_accessor :country_language_map
|
|
43
|
+
|
|
44
|
+
# Logger-compatible object used to surface resolver exceptions at
|
|
45
|
+
# +warn+ level. Default: <tt>Logger.new($stdout)</tt>.
|
|
46
|
+
attr_accessor :logger
|
|
47
|
+
|
|
48
|
+
def initialize
|
|
49
|
+
@default_locale = :en
|
|
50
|
+
@cookie_name = 'locale'
|
|
51
|
+
@cookie_max_age = 365 * 24 * 60 * 60 # one year
|
|
52
|
+
@detect_on_excluded_paths = true
|
|
53
|
+
@geo_resolver = nil
|
|
54
|
+
@user_locale_resolver = nil
|
|
55
|
+
@current_user_resolver = nil
|
|
56
|
+
@country_language_map = LocaleKit::COUNTRY_LANGUAGES
|
|
57
|
+
@logger = ::Logger.new($stdout)
|
|
58
|
+
self.available_locales = [:en]
|
|
59
|
+
self.excluded_paths = ['/assets', '/api', '/favicon.ico', '/robots.txt', '/sitemap.xml']
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Sets the supported locales (strings or symbols; coerced to symbols)
|
|
63
|
+
# and precomputes the path prefixes and the supports? lookup. The
|
|
64
|
+
# locales are also added to +I18n.available_locales+ (union, the
|
|
65
|
+
# host's own extras stay), otherwise +I18n.locale = :sv+ raises
|
|
66
|
+
# I18n::InvalidLocale the moment the middleware applies a locale the
|
|
67
|
+
# host forgot to register with I18n.
|
|
68
|
+
def available_locales=(value)
|
|
69
|
+
@available_locales = Array(value).map(&:to_sym).freeze
|
|
70
|
+
I18n.available_locales |= @available_locales
|
|
71
|
+
@available_locale_lookup = @available_locales.each_with_object({}) do |locale, lookup|
|
|
72
|
+
lookup[locale] = true
|
|
73
|
+
lookup[locale.to_s] = true
|
|
74
|
+
end.freeze
|
|
75
|
+
@locale_path_prefixes = @available_locales.map do |locale|
|
|
76
|
+
prefix = "/#{locale}"
|
|
77
|
+
[prefix, "#{prefix}/", locale]
|
|
78
|
+
end.freeze
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Sets the default locale (string or symbol; coerced to symbol).
|
|
82
|
+
def default_locale=(value)
|
|
83
|
+
@default_locale = value.to_sym
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Sets the excluded paths, normalizing String entries once so
|
|
87
|
+
# request-time matching does not allocate.
|
|
88
|
+
def excluded_paths=(value)
|
|
89
|
+
@excluded_paths = Array(value)
|
|
90
|
+
strings, regexps = @excluded_paths.partition { !it.is_a?(Regexp) }
|
|
91
|
+
@excluded_path_prefixes = strings.map { it.to_s.chomp('/') }.freeze
|
|
92
|
+
@excluded_path_prefix_slashes = @excluded_path_prefixes.map { "#{it}/" }.freeze
|
|
93
|
+
@excluded_path_regexps = regexps.freeze
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Reader/writer pair: pass a block to set, call bare to read. The block
|
|
97
|
+
# receives the current user (from current_user_resolver) and returns a
|
|
98
|
+
# locale symbol/string or +nil+. Errors are logged and swallowed.
|
|
99
|
+
def user_locale_resolver(&block)
|
|
100
|
+
@user_locale_resolver = block if block
|
|
101
|
+
@user_locale_resolver
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Reader/writer pair. The block receives an IP string and returns an
|
|
105
|
+
# ISO 3166-1 alpha-2 country code (case-insensitive) or +nil+. Errors
|
|
106
|
+
# are logged and swallowed.
|
|
107
|
+
def geo_resolver(&block)
|
|
108
|
+
@geo_resolver = block if block
|
|
109
|
+
@geo_resolver
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Reader/writer pair. The block receives the Rack +env+ and returns an
|
|
113
|
+
# opaque user object (forwarded to user_locale_resolver) or +nil+.
|
|
114
|
+
# Called once per request — keep it cheap (session lookup, not an
|
|
115
|
+
# uncached database hit).
|
|
116
|
+
def current_user_resolver(&block)
|
|
117
|
+
@current_user_resolver = block if block
|
|
118
|
+
@current_user_resolver
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Returns +true+ when +locale+ (string or symbol) is in
|
|
122
|
+
# +available_locales+; +false+ for +nil+. One hash lookup, no +to_sym+
|
|
123
|
+
# on unvalidated input.
|
|
124
|
+
def supports?(locale)
|
|
125
|
+
return false if locale.nil?
|
|
126
|
+
|
|
127
|
+
@available_locale_lookup.key?(locale)
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module LocaleKit
|
|
4
|
+
# Default ISO 3166-1 alpha-2 country code → primary language Symbol map
|
|
5
|
+
# for the geo detection step; each multilingual country gets one primary
|
|
6
|
+
# language. Override via Configuration#country_language_map, e.g.
|
|
7
|
+
# <tt>LocaleKit::COUNTRY_LANGUAGES.merge('BE' => :fr)</tt>.
|
|
8
|
+
COUNTRY_LANGUAGES = {
|
|
9
|
+
# EU + EEA
|
|
10
|
+
'AT' => :de, 'BE' => :nl, 'BG' => :bg, 'CH' => :de, 'CY' => :el,
|
|
11
|
+
'CZ' => :cs, 'DE' => :de, 'DK' => :da, 'EE' => :et, 'ES' => :es,
|
|
12
|
+
'FI' => :fi, 'FR' => :fr, 'GB' => :en, 'GR' => :el, 'HR' => :hr,
|
|
13
|
+
'HU' => :hu, 'IE' => :en, 'IS' => :is, 'IT' => :it, 'LI' => :de,
|
|
14
|
+
'LT' => :lt, 'LU' => :fr, 'LV' => :lv, 'MT' => :mt, 'NL' => :nl,
|
|
15
|
+
'NO' => :no, 'PL' => :pl, 'PT' => :pt, 'RO' => :ro, 'SE' => :sv,
|
|
16
|
+
'SI' => :sl, 'SK' => :sk, 'UK' => :en,
|
|
17
|
+
# Americas
|
|
18
|
+
'US' => :en, 'CA' => :en, 'MX' => :es, 'BR' => :pt, 'AR' => :es,
|
|
19
|
+
'CL' => :es, 'CO' => :es, 'PE' => :es, 'VE' => :es, 'UY' => :es,
|
|
20
|
+
# Asia and Pacific
|
|
21
|
+
'JP' => :ja, 'CN' => :zh, 'TW' => :zh, 'HK' => :zh, 'KR' => :ko,
|
|
22
|
+
'IN' => :en, 'ID' => :id, 'MY' => :ms, 'PH' => :en, 'SG' => :en,
|
|
23
|
+
'TH' => :th, 'VN' => :vi, 'AU' => :en, 'NZ' => :en,
|
|
24
|
+
# Middle East and Africa
|
|
25
|
+
'IL' => :he, 'SA' => :ar, 'AE' => :ar, 'EG' => :ar, 'TR' => :tr,
|
|
26
|
+
'ZA' => :en, 'NG' => :en, 'KE' => :en, 'MA' => :ar,
|
|
27
|
+
# Other
|
|
28
|
+
'RU' => :ru, 'UA' => :uk, 'BY' => :be
|
|
29
|
+
}.freeze
|
|
30
|
+
end
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module LocaleKit
|
|
4
|
+
# Walks the detection cascade and returns the first locale found, falling
|
|
5
|
+
# back to +config.default_locale+. Default order: user preference,
|
|
6
|
+
# cookie, +Accept-Language+, IP geolocation.
|
|
7
|
+
#
|
|
8
|
+
# Chain entries are Symbols naming the built-in steps below, or callables
|
|
9
|
+
# receiving <tt>(request, user, config)</tt> and returning a supported
|
|
10
|
+
# locale Symbol or +nil+ to fall through:
|
|
11
|
+
#
|
|
12
|
+
# subdomain = ->(request, _user, config) do
|
|
13
|
+
# sub = request.host.split('.').first.to_sym
|
|
14
|
+
# sub if config.supports?(sub)
|
|
15
|
+
# end
|
|
16
|
+
# Detector.new(config, chain: [subdomain, *Detector::DEFAULT_CHAIN])
|
|
17
|
+
class Detector
|
|
18
|
+
DEFAULT_CHAIN = %i[user_preference cookie accept_language ip_geolocation].freeze
|
|
19
|
+
|
|
20
|
+
def initialize(config, chain: DEFAULT_CHAIN)
|
|
21
|
+
@config = config
|
|
22
|
+
@chain = chain
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Returns the first locale a chain step yields, or +default_locale+.
|
|
26
|
+
# +user+ is the object from Configuration#current_user_resolver.
|
|
27
|
+
def detect(request, user: nil)
|
|
28
|
+
@chain.each do |step|
|
|
29
|
+
locale = step.is_a?(Symbol) ? send(step, request, user) : step.call(request, user, @config)
|
|
30
|
+
return locale if locale
|
|
31
|
+
end
|
|
32
|
+
@config.default_locale
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
# Locale stored on the logged-in user, via user_locale_resolver.
|
|
38
|
+
# Resolver errors are logged at warn and treated as "no preference."
|
|
39
|
+
def user_preference(_request, user)
|
|
40
|
+
return unless user && @config.user_locale_resolver
|
|
41
|
+
|
|
42
|
+
locale = @config.user_locale_resolver.call(user)
|
|
43
|
+
locale.to_sym if @config.supports?(locale)
|
|
44
|
+
rescue StandardError => e
|
|
45
|
+
@config.logger&.warn("[locale_kit] user_locale_resolver raised #{e.class}: #{e.message}")
|
|
46
|
+
nil
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Locale from the preference cookie. The raw-header check avoids
|
|
50
|
+
# Rack's cookie parsing when the cookie can't be present.
|
|
51
|
+
def cookie(request, _user)
|
|
52
|
+
header = request.env['HTTP_COOKIE']
|
|
53
|
+
return unless header&.include?(@config.cookie_name)
|
|
54
|
+
|
|
55
|
+
value = request.cookies[@config.cookie_name]
|
|
56
|
+
value.to_sym if @config.supports?(value)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Highest-ranked supported tag from Accept-Language; a tag falls back
|
|
60
|
+
# to its base language (en-us → en) before losing its turn.
|
|
61
|
+
def accept_language(request, _user)
|
|
62
|
+
header = request.env['HTTP_ACCEPT_LANGUAGE']
|
|
63
|
+
return if header.nil? || header.empty?
|
|
64
|
+
|
|
65
|
+
ranked(header).each do |tag|
|
|
66
|
+
return tag.to_sym if @config.supports?(tag)
|
|
67
|
+
|
|
68
|
+
base = tag.split('-').first
|
|
69
|
+
return base.to_sym if @config.supports?(base)
|
|
70
|
+
end
|
|
71
|
+
nil
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Request IP → country via geo_resolver → language via
|
|
75
|
+
# country_language_map. Resolver errors are logged at warn and
|
|
76
|
+
# treated as "unknown."
|
|
77
|
+
def ip_geolocation(request, _user)
|
|
78
|
+
return unless @config.geo_resolver
|
|
79
|
+
|
|
80
|
+
country = @config.geo_resolver.call(request.ip)
|
|
81
|
+
return unless country
|
|
82
|
+
|
|
83
|
+
language = @config.country_language_map[country.to_s.upcase]
|
|
84
|
+
language.to_sym if @config.supports?(language)
|
|
85
|
+
rescue StandardError => e
|
|
86
|
+
@config.logger&.warn("[locale_kit] geo_resolver raised #{e.class}: #{e.message}")
|
|
87
|
+
nil
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Tags ordered by descending quality. Splits on +;+ and strips so
|
|
91
|
+
# RFC 9110 optional whitespace (<tt>en; q=0.8</tt>) parses like the
|
|
92
|
+
# compact form; +q=0+ means "not acceptable" and is dropped.
|
|
93
|
+
def ranked(header)
|
|
94
|
+
weighted = header.split(',').filter_map do |part|
|
|
95
|
+
tag, _, params = part.partition(';')
|
|
96
|
+
tag = tag.strip.downcase
|
|
97
|
+
next if tag.empty?
|
|
98
|
+
|
|
99
|
+
q = params[/q\s*=\s*([\d.]+)/, 1]&.to_f || 1.0
|
|
100
|
+
next if q <= 0
|
|
101
|
+
|
|
102
|
+
[tag, q]
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
weighted.sort_by { |_, q| -q }.map(&:first)
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
end
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module LocaleKit
|
|
4
|
+
# Instance methods for the routing/view scope. The Roda plugin mixes
|
|
5
|
+
# this in automatically; non-Roda apps can include it wherever +request+
|
|
6
|
+
# and +response+ are available.
|
|
7
|
+
module Helpers
|
|
8
|
+
# Matches strings that are not app-relative paths — any URI scheme
|
|
9
|
+
# (+https:+, +mailto:+, +sms:+, ...) or protocol-relative +//host+.
|
|
10
|
+
# Such strings pass through localized_url unchanged.
|
|
11
|
+
EXTERNAL_URL = %r{\A(?:[a-z][a-z0-9+.-]*:|//)}i
|
|
12
|
+
|
|
13
|
+
# The locale active for the current request, from
|
|
14
|
+
# <tt>env['locale_kit.locale']</tt>; falls back to +I18n.locale+
|
|
15
|
+
# outside a middleware-wrapped request.
|
|
16
|
+
def current_locale
|
|
17
|
+
request.env['locale_kit.locale'] || I18n.locale
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# All supported locales, in configured order.
|
|
21
|
+
def available_locales
|
|
22
|
+
LocaleKit.configuration.available_locales
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Returns +path+ with the current (or given) locale prefix prepended,
|
|
26
|
+
# replacing any existing supported-locale prefix. External URLs
|
|
27
|
+
# (EXTERNAL_URL) and excluded paths pass through unchanged.
|
|
28
|
+
def localized_url(path, locale: current_locale)
|
|
29
|
+
str = path.to_s
|
|
30
|
+
return str if str.match?(EXTERNAL_URL)
|
|
31
|
+
|
|
32
|
+
config = LocaleKit.configuration
|
|
33
|
+
return str if LocaleKit.excluded_path?(str, config)
|
|
34
|
+
|
|
35
|
+
LocaleKit.localize_path(locale, str, config)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Persists +locale+ in the preference cookie (SameSite=Lax, readable by
|
|
39
|
+
# client-side switchers) and sets +I18n.locale+ for the rest of the
|
|
40
|
+
# request. Unsupported values are silently ignored.
|
|
41
|
+
def set_user_locale(locale) # rubocop:disable Naming/AccessorMethodName -- public API, a verb phrase with side effects, not an attribute writer
|
|
42
|
+
locale = locale.to_sym
|
|
43
|
+
return unless LocaleKit.configuration.supports?(locale)
|
|
44
|
+
|
|
45
|
+
response.set_cookie(
|
|
46
|
+
LocaleKit.configuration.cookie_name,
|
|
47
|
+
value: locale.to_s,
|
|
48
|
+
path: '/',
|
|
49
|
+
max_age: LocaleKit.configuration.cookie_max_age,
|
|
50
|
+
secure: request.ssl?,
|
|
51
|
+
same_site: :lax,
|
|
52
|
+
httponly: false
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
I18n.locale = locale
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The current request path under a different locale prefix. Useful for
|
|
59
|
+
# hreflang tags and custom switchers.
|
|
60
|
+
def path_with_locale(locale)
|
|
61
|
+
LocaleKit.localize_path(locale, request.path_info)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
end
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module LocaleKit
|
|
4
|
+
# Rack middleware that performs the URL-prefix locale handling. The Roda
|
|
5
|
+
# plugin inserts it automatically; any Rack app can +use+ it directly.
|
|
6
|
+
#
|
|
7
|
+
# Per request:
|
|
8
|
+
#
|
|
9
|
+
# 1. Excluded path: run detection so +I18n.locale+ is still set (unless
|
|
10
|
+
# Configuration#detect_on_excluded_paths is +false+), pass through.
|
|
11
|
+
# 2. Supported locale prefix (+/sv/...+): strip it from +PATH_INFO+, set
|
|
12
|
+
# the locale, pass downstream.
|
|
13
|
+
# 3. Otherwise: detect. HTML +GET+ requests get a 302 to
|
|
14
|
+
# <tt>/{locale}{path}</tt> (query string and +SCRIPT_NAME+ preserved);
|
|
15
|
+
# everything else passes through with the locale set in place.
|
|
16
|
+
#
|
|
17
|
+
# Sets <tt>env['locale_kit.locale']</tt> and +I18n.locale+ (when I18n is
|
|
18
|
+
# loaded) on every request it detects or extracts a locale for.
|
|
19
|
+
class Middleware
|
|
20
|
+
def initialize(app)
|
|
21
|
+
@app = app
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def call(env)
|
|
25
|
+
path = env['PATH_INFO']
|
|
26
|
+
config = LocaleKit.configuration
|
|
27
|
+
|
|
28
|
+
if LocaleKit.excluded_path?(path, config)
|
|
29
|
+
if config.detect_on_excluded_paths
|
|
30
|
+
request = Rack::Request.new(env)
|
|
31
|
+
apply_locale(env, LocaleKit.detect(request, user: current_user(config, env)))
|
|
32
|
+
end
|
|
33
|
+
return @app.call(env)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
locale, remaining = LocaleKit.split_locale_prefix(path, config)
|
|
37
|
+
|
|
38
|
+
if locale
|
|
39
|
+
env['PATH_INFO'] = remaining
|
|
40
|
+
apply_locale(env, locale)
|
|
41
|
+
@app.call(env)
|
|
42
|
+
else
|
|
43
|
+
detect_and_dispatch(env, config, path)
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private
|
|
48
|
+
|
|
49
|
+
# No supported prefix: detect, then redirect HTML GETs to the
|
|
50
|
+
# localized path and pass everything else through with the locale
|
|
51
|
+
# applied in place.
|
|
52
|
+
def detect_and_dispatch(env, config, path)
|
|
53
|
+
request = Rack::Request.new(env)
|
|
54
|
+
detected = LocaleKit.detect(request, user: current_user(config, env))
|
|
55
|
+
apply_locale(env, detected)
|
|
56
|
+
|
|
57
|
+
if env['REQUEST_METHOD'] == 'GET' && wants_html?(env)
|
|
58
|
+
redirect_to_localized(env, detected, path)
|
|
59
|
+
else
|
|
60
|
+
@app.call(env)
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def current_user(config, env)
|
|
65
|
+
config.current_user_resolver&.call(env)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# i18n is a hard dependency required by locale_kit.rb, so no guard.
|
|
69
|
+
def apply_locale(env, locale)
|
|
70
|
+
env['locale_kit.locale'] = locale
|
|
71
|
+
I18n.locale = locale
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def wants_html?(env)
|
|
75
|
+
accept = env['HTTP_ACCEPT'].to_s
|
|
76
|
+
return true if accept.empty?
|
|
77
|
+
|
|
78
|
+
accept.include?('text/html') || accept.include?('*/*')
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def redirect_to_localized(env, locale, path)
|
|
82
|
+
target = "#{env['SCRIPT_NAME']}/#{locale}#{path unless path == '/'}"
|
|
83
|
+
query_string = env['QUERY_STRING'].to_s
|
|
84
|
+
target += "?#{query_string}" unless query_string.empty?
|
|
85
|
+
|
|
86
|
+
[302, { 'location' => target, 'content-type' => 'text/html', 'content-length' => '0' }, []]
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
data/lib/locale_kit.rb
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'i18n'
|
|
4
|
+
|
|
5
|
+
require 'locale_kit/version'
|
|
6
|
+
require 'locale_kit/country_languages'
|
|
7
|
+
require 'locale_kit/configuration'
|
|
8
|
+
require 'locale_kit/detector'
|
|
9
|
+
require 'locale_kit/middleware'
|
|
10
|
+
require 'locale_kit/helpers'
|
|
11
|
+
|
|
12
|
+
# URL-prefix locale handling for Ruby web apps: serves a multilingual site
|
|
13
|
+
# under +/sv/+, +/en/+ style URLs without the locale appearing in any route.
|
|
14
|
+
# Roda apps load Roda::RodaPlugins::LocaleKit (<tt>plugin :locale_kit</tt>);
|
|
15
|
+
# any Rack app can +use LocaleKit::Middleware+ directly. See README.md for
|
|
16
|
+
# the full guide and LocaleKit::Configuration for all settings.
|
|
17
|
+
module LocaleKit
|
|
18
|
+
class << self
|
|
19
|
+
# Yields the singleton Configuration and returns it. Call at boot;
|
|
20
|
+
# repeated calls merge into the same configuration.
|
|
21
|
+
def configure
|
|
22
|
+
yield configuration if block_given?
|
|
23
|
+
@detector = nil
|
|
24
|
+
configuration
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# The process-wide Configuration, created with defaults on first access.
|
|
28
|
+
def configuration
|
|
29
|
+
@configuration ||= Configuration.new
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Shortcut for <tt>configuration.logger</tt>.
|
|
33
|
+
def logger
|
|
34
|
+
configuration.logger
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Runs the detection cascade for a Rack +request+; always returns a
|
|
38
|
+
# locale Symbol. +user+ is forwarded to the user-preference step.
|
|
39
|
+
def detect(request, user: nil)
|
|
40
|
+
(@detector ||= Detector.new(configuration)).detect(request, user: user)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Splits +path+ into <tt>[locale, remaining_path]</tt> when the first
|
|
44
|
+
# segment is a supported locale, or <tt>[nil, path]</tt> otherwise.
|
|
45
|
+
def split_locale_prefix(path, config = configuration)
|
|
46
|
+
config.locale_path_prefixes.each do |exact_prefix, slash_prefix, locale|
|
|
47
|
+
return [locale, '/'] if path == exact_prefix
|
|
48
|
+
return [locale, path.byteslice(exact_prefix.length..)] if path.start_with?(slash_prefix)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
[nil, path]
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Returns +path+ with any supported-locale prefix removed; unsupported
|
|
55
|
+
# prefixes are left intact.
|
|
56
|
+
def strip_locale_prefix(path, config = configuration)
|
|
57
|
+
locale, remaining = split_locale_prefix(path, config)
|
|
58
|
+
locale ? remaining : path
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Returns +path+ prefixed with +locale+, stripping any existing
|
|
62
|
+
# supported-locale prefix first so paths are never double-prefixed.
|
|
63
|
+
#
|
|
64
|
+
# LocaleKit.localize_path(:sv, '/en/users') # => '/sv/users'
|
|
65
|
+
# LocaleKit.localize_path(:sv, '/') # => '/sv'
|
|
66
|
+
def localize_path(locale, path, config = configuration)
|
|
67
|
+
stripped = strip_locale_prefix(path, config)
|
|
68
|
+
stripped == '/' ? "/#{locale}" : "/#{locale}#{stripped}"
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Returns +true+ when +path+ matches Configuration#excluded_paths.
|
|
72
|
+
# String entries match as path prefixes; Regexps match the full path.
|
|
73
|
+
def excluded_path?(path, config = configuration)
|
|
74
|
+
return true if config.excluded_path_prefixes.include?(path) ||
|
|
75
|
+
path.start_with?(*config.excluded_path_prefix_slashes)
|
|
76
|
+
|
|
77
|
+
config.excluded_path_regexps.any? { it.match?(path) }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Replaces the configuration with a fresh default one. For test hooks.
|
|
81
|
+
def reset! # :nodoc:
|
|
82
|
+
@configuration = Configuration.new
|
|
83
|
+
@detector = nil
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'locale_kit'
|
|
4
|
+
|
|
5
|
+
class Roda
|
|
6
|
+
module RodaPlugins
|
|
7
|
+
# The +:locale_kit+ plugin wires LocaleKit into a Roda app: it inserts
|
|
8
|
+
# LocaleKit::Middleware, mounts a <tt>POST /locale/:locale</tt> switcher
|
|
9
|
+
# route, mixes LocaleKit::Helpers into the routing scope, and wraps the
|
|
10
|
+
# +:path+ plugin's helpers (named routes, object form, +url+, and
|
|
11
|
+
# +link_to+) so generated links carry the current locale prefix.
|
|
12
|
+
# Loading the plugin twice is a no-op. Configure via LocaleKit.configure;
|
|
13
|
+
# see README.md for the guide.
|
|
14
|
+
#
|
|
15
|
+
# class App < Roda
|
|
16
|
+
# plugin :locale_kit
|
|
17
|
+
# end
|
|
18
|
+
#
|
|
19
|
+
# The switcher sets the locale cookie and redirects to +return_to+,
|
|
20
|
+
# which must be an app-relative path starting with +/+ — anything else
|
|
21
|
+
# (absolute URLs, non-String values, missing) falls back to +/+.
|
|
22
|
+
# Unsupported locales get a 404.
|
|
23
|
+
module LocaleKit
|
|
24
|
+
def self.load_dependencies(app)
|
|
25
|
+
app.plugin :path
|
|
26
|
+
app.plugin :hash_branches
|
|
27
|
+
app.plugin :cookies
|
|
28
|
+
app.plugin :link_to
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def self.configure(app)
|
|
32
|
+
return if app.opts[:locale_kit]
|
|
33
|
+
|
|
34
|
+
app.opts[:locale_kit] = true
|
|
35
|
+
|
|
36
|
+
app.use ::LocaleKit::Middleware
|
|
37
|
+
|
|
38
|
+
app.hash_branch('locale') do |r|
|
|
39
|
+
r.post(String) do |target|
|
|
40
|
+
# Enforced only when :route_csrf is loaded; a forged POST
|
|
41
|
+
# could otherwise pin a victim's locale.
|
|
42
|
+
check_csrf! if respond_to?(:check_csrf!)
|
|
43
|
+
target_locale = target.to_sym
|
|
44
|
+
|
|
45
|
+
if ::LocaleKit.configuration.supports?(target_locale)
|
|
46
|
+
set_user_locale(target_locale)
|
|
47
|
+
return_to = r.params['return_to']
|
|
48
|
+
return_to = '/' unless return_to.is_a?(String) && return_to.start_with?('/')
|
|
49
|
+
r.redirect(::LocaleKit.localize_path(target_locale, return_to))
|
|
50
|
+
else
|
|
51
|
+
response.status = 404
|
|
52
|
+
''
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
module ClassMethods
|
|
59
|
+
# Wraps named-route helpers from the +:path+ plugin (e.g.
|
|
60
|
+
# +users_path+) to return locale-prefixed paths. Class-form
|
|
61
|
+
# registrations and +:url_only+ pass through; the object form is
|
|
62
|
+
# handled by InstanceMethods#path.
|
|
63
|
+
def path(name, path = nil, opts = OPTS, &)
|
|
64
|
+
result = super
|
|
65
|
+
return result if name.is_a?(Class)
|
|
66
|
+
return result if opts.is_a?(Hash) && opts[:url_only]
|
|
67
|
+
|
|
68
|
+
meth = (opts.is_a?(Hash) && opts[:name]) || "#{name}_path"
|
|
69
|
+
return result unless method_defined?(meth)
|
|
70
|
+
|
|
71
|
+
original = instance_method(meth)
|
|
72
|
+
define_method(meth) do |*args, &blk|
|
|
73
|
+
generated = original.bind_call(self, *args, &blk)
|
|
74
|
+
generated.is_a?(String) ? localized_url(generated) : generated
|
|
75
|
+
end
|
|
76
|
+
result
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
module InstanceMethods
|
|
81
|
+
include ::LocaleKit::Helpers
|
|
82
|
+
|
|
83
|
+
# Auto-localizes the object form +path(@obj)+; +url+ inherits the
|
|
84
|
+
# prefix because the +:path+ plugin builds it on top of +path+.
|
|
85
|
+
def path(*args, &)
|
|
86
|
+
generated = super
|
|
87
|
+
generated.is_a?(String) ? localized_url(generated) : generated
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Auto-localizes String hrefs; Symbol and object hrefs are already
|
|
91
|
+
# covered by the +path+ overrides.
|
|
92
|
+
def link_to(body, href, attributes = OPTS)
|
|
93
|
+
href = localized_url(href) if href.is_a?(String)
|
|
94
|
+
super
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
register_plugin(:locale_kit, LocaleKit)
|
|
100
|
+
end
|
|
101
|
+
end
|