Show HN: Don’t set your website language based on user location

Show HN: Don’t set your website language based on user location

I was in dismay studying End environment the language of your net blueprint in response to user situation. The sheer simplicity of that concept and the have an effect on is huge.

Want an occasion? I at all times ship a VPN. Chrome is house to English for me. My VPN was once house to Germany. I refreshed the Google Adsense web web page I was taking a peek at and received mechanically redirected to the .de web web page.

Whereas Pedro Pimenta’s article suggests the ship of javascript to house the locale, right here is on the whole unfeasible because the translations are carried out server-aspect. Let’s salvage a peek at an means to make this in Rails.

Fortunately, the language is house as an HTTP header. Purchase a peek at mine:

settle for-language: en-GB,en-US;q=0.9,en;q=0.8

Let’s wreck it down. Some languages cling q-values — the relative quality factor (it specifies what language the consumer would buy on a scale of Zero to 1).

In Ruby on Rails, that you just may probably earn admission to HTTP headers in a controller with quiz.env['HTTP_ACCEPT_LANGUAGE']. You’ll be in a blueprint to parse this string the ship of the http-settle for gem.

languages = HTTP::Accept::Languages.parse("en-GB,en-US;q=0.9,en;q=0.8")languages[0].locale # en-gb

Now, we will house this locale the ship of the approaches suggested by the Rails Guides. In ApplicationController, we should clean house an around_action

around_action : set_localeinside mostdef set_locale(&motion)

languages = HTTP::Accept::Languages.parse(quiz.env['HTTP_ACCEPT_LANGUAGE'])
locale = languages[0]&.locale || I18n.default_locale I18n.with_locale(locale, &motion)discontinue


Please enter your comment!
Please enter your name here