Get locale from HTTP request

suggest change

Sometimes it can be useful to set your application locale based upon the request IP. You can easily achieve this using Geocoder. Among the many things Geocoder does, it can also tell the location of a request.

First, add Geocoder to your Gemfile

# Gemfile
gem 'geocoder'

Geocoder adds location and safe_location to Rack::Request, so you can look up the location of an HTTP request by IP address. Call it from a before_action:

class ApplicationController < ActionController::Base
  before_action :set_locale_from_request

  def set_locale_from_request
    country_code = request.location.data["country_code"] #=> "US"
    country_sym = country_code.underscore.to_sym #=> :us

    # A country code is not an I18n locale. Locales are usually :en or :de.
    # Map the country to a locale you actually ship before assigning it.
    if I18n.available_locales.include?(country_sym)
      I18n.locale = country_sym
    end
  end
end

This does not work in development and test for addresses such as 0.0.0.0 and localhost. Those are not public Internet addresses. Configure a lookup service and use a public IP.


Limitations and alternatives

Geocoder is very powerful and flexible, but needs to be configured to work with a geocoding service (see more details); many of which place limits on usage. It’s also worth bearing in mind that calling an external service on every request could impact performance.

To address these, it can also be worth considering:

1. An offline solution

Using a gem like GeoIP (see here) allows lookups to happen against a local datafile. There may be a trade-off in terms of accuracy, as these datafiles need to be kept up-to-date.

2. Use Cloudflare

Pages served through Cloudflare can be geocoded at the edge. The country code is added as the CF-IPCountry header (HTTP_CF_IPCOUNTRY in Rack). In Rails, read request.headers["CF-IPCountry"]. More detail is in the Cloudflare geolocation article.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents