Rails include many mechanisms based on the location of visitors to display information that corresponds to their geographical context without requiring too much effort on the part of developers. The I18n Internationalization API, an integral part of Rails since version 2.2, provides a powerful framework for creating multilingual applications. I18n manages translations, date and time formats, names of days and months, pluralization rules, and much more. This is also a common requirement on web apps, where due to regulations like GDPR in the European Union you need the user's explicit consent via cookie banner.
For example, the helper method number_to_currency, which takes an integer or decimal number as input, returns a string representing a price formatted according to the requested locale.
Displaying a price formatted in the visitor's locale is very easy in Rails, but it remains the developer's responsibility to convert currency values, which is out of the scope of this article.
To translate all the string used by core Rails, you need only to install the rails-i18n gem, which provides the translation in more than a hundred languages. You can also write your own translation in the files located in the config/locales directory.
Add one of the following lines to your Gemfile:
Then update your bundle:
You must then set up a mechanism that allows the controller to determine which locale to use for the current request. Here is the list of elements to consider:
You can implement this function in a before_action of all your controllers:
You also need to save the selected locale in the user's session:
One of the most convenient features for a website is to automatically detect new visitors' geographical location and display itself in the locality corresponding to their region. This can be implemented through geolocation.
Install the geoip gem in your Gemfile:
Then update your bundle:
Download the geolocation database from the MaxMind website, and extract the files in your Rails directory.
You can then use the gem's API to obtain the geographical location of your visitor from their IP address:
However, this is not the easiest method, mainly because it requires a lot of maintenance as you will have to regularly download every MaxMind database updates in order to keep your geolocation accurate. It may not contain all the information you need, such as whether the IP address is using a VPN or proxy service.
A simple and very effective alternative is to use the free Abstract API geolocation service. A simple HTTP call allows determining a user's locale, and the Abstract database always remains up-to-date without requiring any maintenance from you. This is how to integrate it in your controllers: