Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save hemalich/785972 to your computer and use it in GitHub Desktop.

Select an option

Save hemalich/785972 to your computer and use it in GitHub Desktop.
Setting the Locale from the Domain Name ApplicationController
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_tld
end
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
# 127.0.0.1 example.com
# 127.0.0.1 example.it
# 127.0.0.1 example.pl
# in your /etc/hosts file to try this out locally
@u007

u007 commented Jan 23, 2017

Copy link
Copy Markdown
#using accept-language
def set_locale
    accept_lang = request.headers['Accept-Language'].to_s.split(",").first.split("-")[0] rescue ''
    unless accept_lang.blank?
      Rails.logger.info "accept-lang: #{accept_lang}"
      I18n.locale = accept_lang
      return
    end

    I18n.locale = 'en'
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment