Skip to content

Commit 79ab6d3

Browse files
committed
Default Accept-Language to I18n.default_locale
Currently AutoLocale tries to set `I18n.locale` to nil when the Accept-Language header is missing, which leads to "nil is not a valid locale" error when `I18n.config.enforce_available_locales` is true (default). This commit fixes the problem by defaulting the header value to `I18n.default_locale`.
1 parent 5073e34 commit 79ab6d3

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/http_accept_language/auto_locale.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ module AutoLocale
1111
private
1212

1313
def set_locale
14-
I18n.locale = http_accept_language.compatible_language_from(I18n.available_locales)
14+
hal = http_accept_language
15+
hal.header ||= I18n.default_locale.to_s
16+
I18n.locale = hal.compatible_language_from(I18n.available_locales)
1517
end
1618
end
1719
end

spec/auto_locale_spec.rb

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,24 @@
66
describe HttpAcceptLanguage::AutoLocale do
77
let(:controller_class) do
88
Class.new do
9+
def initialize(header = nil)
10+
super()
11+
@header = header
12+
end
13+
914
def self.before_filter(dummy)
1015
# dummy method
1116
end
1217

1318
def http_accept_language
14-
HttpAcceptLanguage::Parser.new("ja,en-us;q=0.7,en;q=0.3")
19+
@http_accept_language ||= HttpAcceptLanguage::Parser.new(@header)
1520
end
1621

1722
include HttpAcceptLanguage::AutoLocale
1823
end
1924
end
2025

21-
let(:controller) { controller_class.new }
26+
let(:controller) { controller_class.new("ja,en-us;q=0.7,en;q=0.3") }
2227

2328
context "available languages includes accept_languages" do
2429
before do
@@ -31,4 +36,19 @@ def http_accept_language
3136
expect(I18n.locale).to eq(:ja)
3237
end
3338
end
39+
40+
let(:no_accept_language_controller) { controller_class.new() }
41+
42+
context "default locale is ja" do
43+
before do
44+
I18n.default_locale = :ja
45+
I18n.available_locales = [:en, :ja]
46+
end
47+
48+
it "set the locale to default" do
49+
no_accept_language_controller.send(:set_locale)
50+
51+
expect(I18n.locale).to eq(:ja)
52+
end
53+
end
3454
end

0 commit comments

Comments
 (0)