Skip to content

Commit ae74d42

Browse files
committed
Ensure locales always behave as expected
1 parent cdbc17d commit ae74d42

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/browserino/methods.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,30 @@ def self.analyze(uas, matcher = nil, headers = nil)
1313
props = fill_missing_with_headers headers, props
1414
end
1515

16+
props = fix_inconsistent_props props
17+
1618
like = Client.new props.merge(like_attrs(props, like, uas)) if like
1719

1820
Client.new props, like
1921
end
2022

23+
def self.fix_inconsistent_props(hsh)
24+
# patch locale and locales props
25+
if hsh[:locales].any?
26+
# when locale is not present in locales, append it
27+
hsh[:locales] << hsh[:locale] unless hsh[:locales].include? hsh[:locale]
28+
29+
# ensure locales.first == locale when locale present in locales
30+
hsh[:locale] = hsh[:locales].first
31+
elsif hsh[:locale]
32+
# no locales from header but locale is found in UA, append locale
33+
# to locales to ensure expected output
34+
hsh[:locales] << hsh[:locale]
35+
end
36+
37+
hsh
38+
end
39+
2140
def self.normalize_header_keys(headers)
2241
headers.each_with_object({}) do |(header, value), normalized|
2342
header = header.gsub(/^HTTP_/i, '').tr('-', '_').downcase.to_sym

spec/missing_props_spec.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,32 @@
3939
expect(client.locale).to be_nil
4040
expect(client.locales).to eq %i[]
4141
end
42+
43+
it 'prefers http header locale over user agent when possible' do
44+
client = Browserino.parse(
45+
'Mozilla/5.0 (Linux; Android 5.1; ZTE Blade L6 Build/LMY47I it-IT) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.91 Mobile Safari/537.36',
46+
{'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.9,nl-NL;q=0.8,nl;q=0.7'}
47+
)
48+
49+
expect(client.locale).to eq :en_us
50+
expect(client.locales).to include :it_it
51+
end
52+
53+
it 'adds locale to locales when locale is found in UA but no headers are given' do
54+
client = Browserino.parse 'Mozilla/5.0 (Linux; Android 5.1; ZTE Blade L6 Build/LMY47I it-IT) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.91 Mobile Safari/537.36'
55+
56+
expect(client.locale).to eq :it_it
57+
expect(client.locales).to include :it_it
58+
end
59+
60+
it 'sets locale to locales.first when locale is found in headers but not in UA' do
61+
client = Browserino.parse(
62+
'Mozilla/5.0 (Linux; Android 5.1; ZTE Blade L6 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.91 Mobile Safari/537.36',
63+
{'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.9,nl-NL;q=0.8,nl;q=0.7'}
64+
)
65+
66+
expect(client.locale).to eq :en_us
67+
expect(client.locales).to include :en_us
68+
end
4269
end
4370
end

0 commit comments

Comments
 (0)