This repository was archived by the owner on Sep 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathauto_locale.rb
58 lines (54 loc) · 1.5 KB
/
auto_locale.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module AutoLocale
module Helpers
##
# This reload the page changing the I18n.locale
#
def switch_to_lang(lang)
return unless settings.locales.include?(lang)
if request.path_info[/\/#{I18n.locale}(\/|$)/]
request.path_info.sub(/\/#{I18n.locale}/, "/#{lang}")
else
request.path_info.sub(/\/$/, "/#{lang}")
end
end
end # Helpers
def self.registered(app)
app.helpers AutoLocale::Helpers
app.extend ClassMethods
app.set :locales, [:en]
app.before do
if request.path_info =~ /^\/(#{settings.locales.join('|')})\b/
I18n.locale = $1.to_sym
elsif request.env['HTTP_ACCEPT_LANGUAGE']
# Guess the preferred language from the browser settings
for browser_locale in request.env['HTTP_ACCEPT_LANGUAGE'].split(",")
locale, usage = browser_locale.split(";")
if settings.locales.include?(locale.to_sym)
I18n.locale = locale.to_sym
break
end
end
# If none found use the default locale
I18n.locale ||= settings.locales[0]
end
end
def parse_route(path, options, verb)
result = super
path = result.first
path = "/(:locale)#{path}"
result[0] = path
result
end
end
module ClassMethods
##
# We need to add always a lang to all our routes
#
def url(*args)
params = args.extract_options!
params[:locale] ||= I18n.locale
args << params
super(*args)
end
end
end