Ruby on Rails - get locale from HTTP request in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
- It can be useful to set our 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.
Add Geocoder to our Gemfile
- Geocoder adds location and safe_location methods to the standard Rack::Request object so we can easily look up the location of any HTTP request by IP address.
- We can use this methods in a before_action in our ApplicationController:
Beware that this will not work in development and test environments, as things like 0.0.0.0 and localhost are valid valid Internet IP addresses.
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:
An offline solution
Using a gem like GeoIP 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.
Use CloudFlare
Pages served through CloudFlare have the option of being geocoded transparently, with the country code being added to the header (HTTP_CF_IPCOUNTRY)