Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/fast_gettext/storage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ def default_locale
# IE6/7 de
# nil if nothing matches
def best_locale_in(locales)
formatted_sorted_locales(locales).each do |candidate|
candidates = plain_locale(locales) || formatted_sorted_locales(locales)
candidates.each do |candidate|
return candidate unless available_locales
return candidate if available_locales.include?(candidate)
return candidate[0..1] if available_locales.include?(candidate[0..1]) # available locales include a langauge
Expand All @@ -160,6 +161,15 @@ def silence_errors

private

# A single locale already in the de / de_DE form, as set_locale gets it on
# every I18n.locale= or with_locale (gettext_i18n_rails): parsing it as
# an Accept-Language header would give the same one candidate.
PLAIN_LOCALE = /\A[a-z]{2,3}(?:_[A-Z]{2,3})?\z/
def plain_locale(locale)
locale = locale.name if locale.is_a?(Symbol)
[locale.dup] if locale.is_a?(String) && PLAIN_LOCALE.match?(locale)
end

# de-de,DE-CH;q=0.9 -> ['de_DE','de_CH']
def formatted_sorted_locales(locales)
found = weighted_locales(locales).reject(&:empty?).sort_by(&:last).reverse # sort them by weight which is the last entry
Expand Down
26 changes: 26 additions & 0 deletions spec/fast_gettext/storage_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,32 @@ def thread_safe(method, value_a, value_b)
FastGettext.locale.should == 'de'
end

it "sets a single locale as it would from a header with only that locale" do
[nil, ['de_DE', 'en', 'pt']].each do |available|
FastGettext.available_locales = available
['en', :en, 'de_DE', :de_DE, 'de-de', 'de_AT', 'pt_BR', 'fr', 'EN', 'zh_Hant', ''].each do |input|
from_header = FastGettext.send(:best_locale_in, "#{input},") # not a single locale: parsed
FastGettext.send(:best_locale_in, input).should == from_header
end
end
end

it "does not parse a single locale as a header" do
FastGettext.available_locales = ['de', 'en']
FastGettext.should_not_receive(:formatted_sorted_locales)
FastGettext.locale = :de
FastGettext.locale.should == 'de'
end

it "does not hand out the string it was given" do
FastGettext.available_locales = nil
given = +'en'
FastGettext.locale = given
FastGettext.locale.should == 'en'
FastGettext.locale.should_not equal(given)
FastGettext.locale.should_not be_frozen
end

it "sets locale from comma seperated" do
FastGettext.available_locales = ['de_DE','en','xx']
FastGettext.locale = "de,de-de,en"
Expand Down
Loading