DonMB
DonMB

Reputation: 2728

Rails: set local to "en" when .co.uk domain

http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name

Works great with .de or other domains. But for English speaking domains, I am using an en.yml. I have tried to implement an exception in my application controller like this:

if I18n.available_locales.map(&:to_s) == "co.uk"
  I18n.locale = "en"
end

But that won't work. I don't want to do this via default locale which is the only solution that comes in my mind now.

How can I tell rails to use the "en" locale if I am on a .co.uk domain without setting the default locale to en?

Upvotes: 1

Views: 170

Answers (1)

dax
dax

Reputation: 10997

The documentation you linked to recommended the following method

before_action :set_locale

def set_locale
  I18n.locale = extract_locale_from_tld || I18n.default_locale
end

def extract_locale_from_tld
  parsed_locale = request.host.split('.').last
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end

Try using this instead. It's cleaner and easier to understand:

before_action :set_locale

...
private

def set_locale
  parsed_locale = request.host.split('.').last
  case parsed_locale
    when 'de' then Il8n.locale = :de
    when 'fr' then Il8n.locale = :fr
    ...
  else 
    I18n.locale = :en  #this is now your 'default'
  end
end

Upvotes: 1

Related Questions