Time ago in words i18n - ruby-on-rails

Is there way to get time_ago_in_words in different languages, or write locales?

Here’s my investigation:
time_ago_in_words calls distance_of_time_in_words (https://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words)
The api docs for that method mention translations in the scope of datetime.distance_in_words.
If you look for distance_in_words in a default locale, such as this en.yml (https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml) you’ll see all the available translations in that space. You can redefine any of these in your locale file.
If, however, you’re just trying to change the language it uses, it seems I18n contains a great many default locales, you need to set the locale either as a default within your app, or from the locale defined in the browser.
To set the default for the app, you’ll need a line like this in config/application.rb
config.i18n.default_locale = :de
You can see the list of default locales here (use the part before .yml) https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale

You can look at the rails i18 locale file en.yml https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml and can use their predefined translations. If you want to change the translations you can also override the en.yml file in your repository.

Related

Rails 5 - Problem with Umlaute and parameterize method

I work on Rails 5.2.3 and Ruby 2.5.1. At some point, I found an issue when I expected my array-of-string constant to contain some string but it didn't. Turned out the problem was related to German Umlaute characters (öäü).
So I have the constant defined like the following:
# coding: utf-8
# frozen_string_literal: true
class MyClass
module MyModule
MY_CONSTANT = [
'Breite in mm',
'Höhe in mm',
'Länge in mm'
].map(&:parameterize).freeze
end
end
I expect the constant to look like ["breite-in-mm", "hoehe-in-mm", "laenge-in-mm"]
But instead it's stored as ["breite-in-mm", "hohe-in-mm", "lange-in-mm"]. You see, "ö" has been converted to "o" instead of "oe". Same for "ä". Now it's "a", not "ae".
It works this way on production, in RSpec tests and even when I start Rails console and call this constant. But when I define a new constant from Rails console using the very same code, the strings are being successfully converted to what I expect, i.e. ["breite-in-mm", "hoehe-in-mm", "laenge-in-mm"]
I could easily get rid of this parameterize method and just type in the strings as I need them. Maybe I will have to do that. But I'm really curious about why all this is happening and couldn't find an answer by myself.
So thank you in advance for any ideas.
The parameterize method in Rails (through its use of ActiveSupport::Inflector#transliterate) is in locale aware. It thus uses locale-depending rules to transliterate characters such as Umlauts to ASCII characters.
When your app handles a request (or at least once after booting), you are usually setting a I18n locale, e.g. with I18n.locale = :de for a single request or with I18n.default_locale = :de for your whole app. After that, Rails (resp. the i18n gem) used this locale by default for its transliteration rules.
When initially setting your constant, this default locale was likely not yet set. The i18n gem is thus not aware of the German transliteration rules and uses only the basic Unicode normalization rules.
As a workaround, you can either pass the desired locale to use to the parameterize method as
MY_CONSTANT = [
'Breite in mm',
'Höhe in mm',
'Länge in mm'
].map { |const| const.parameterize(locale: :de).freeze }.freeze
or you can alternatively set the default i18n locale earlier than when your code is executed (e.g. in a file in config/initializers, depending on where exactly you initialize your constant):
I18n.default_locale = :de
Thanks, Holger Just for your great answer. It seems to be correct except it only works for Rails 6.0.0. So I'm going to post the one for Rails 5.2.3 which I'm using on my project.
Unfortunately in Rails 5 parameterize method does not accept the locale argument yet. This will be possible only in Rails 6.
But still, as mentioned in Holger Just's answer, parameterize method relies on transliterate method which does actually use current locale and converts strings according to it.
See Rails 5.2.3 docs and sources for those methods:
https://api.rubyonrails.org/v5.2.3/classes/ActiveSupport/Inflector.html#method-i-parameterize
https://api.rubyonrails.org/v5.2.3/classes/ActiveSupport/Inflector.html#method-i-transliterate
So I cannot pass the locale to parameterize method directly. Then I should set the locale before my constant is defined.
Setting I18n.default_locale = :de inside application.rb file did not help. I already had that and the strings have been transliterated regardless.
What eventually helped was setting I18n.locale = :de manually. Thanks to this, I got my strings parameterized correctly without any changes to MyConstant definition.

Rails 4.1 locale and 'version' based on url (.com, .cz, .de, etc)

Hope somebody can point me at the right direction with this...
Basically, i have the locales setup and it works fine. However, i need to depending on how the user gets to the site (example_company.com, example_company.cz or example_company.de..) have slightly different content(views and layout).
I've managed to boil it down to a constant or env variable that if i was to run multiple instances of the site(1 for each country), i could set on the server so that i get the behaviour i need with 1 code base.
My question is, how are people dealing with this in general? is there any way i can serve all countries on the same instance and set some flag based on .com or .cz or whatever, that dictates which 'version' they get without effecting the url itself?
I already have the locales in the url and would prefer not to mix the two as i will have to support multiple languages for each version. For example, french and czech would still support english.. But if i go to the french one, i will only show 2 locales (french and english)...
Hope i managed to explain properly.. if not let me know and i will try again.
If you use Rails' built-in i18n support, you can easily select locales by TLD.
From the official Rails i18n guide:
One option you have is to set the locale from the domain name where your application runs. For example, we want www.example.com to load the English (or default) locale, and www.example.es to load the Spanish locale. Thus the top-level domain name is used for locale setting. This has several advantages:
The locale is an obvious part of the URL.
People intuitively grasp in which language the content will be displayed.
It is very trivial to implement in Rails.
Search engines seem to like that content in different languages lives at different, inter-linked domains.
You can implement it like this in your ApplicationController:
before_action :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
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 application.com
# 127.0.0.1 application.it
# 127.0.0.1 application.pl
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
Be sure to read the i18n guide in full. It covers how to use the built-in i18n support. A big advantage is you don't need separate views for each locale.

What's the difference between Globalize.with_locale and I18n.with_locale?

I found both methods to work but I don't want strange surprises: what' the difference between them? Can I use one or another without problems?
Both methods effectively do the same thing:
Record what the current locale is
Set the locale to the specified locale
Run the provided block of code
Set the locale back to the recorded locale
I18n will fetch translations from its locale files, whereas globalize will fetch translations from its database store.

Rails 3 available_locales excluding gem translations

I have a Rails 3 app in which I'm using I18n.available_locales to display a list of available languages for user accounts. In my config/locales directory I only have en and nl yml files, however, I18n.available_locales returns a variety of other locale keys which I'm assuming are present due to translations being present in the gems that I'm using. Is there a common/standard way to get the method to only return the translations present in the app itself?
I would suggest, you use this gem : rails-i18n , it provides basic translations for every languages, and then, restrict available locales with
config.i18n.available_locales = ['es-CO', :de]
Of course, rails-i18n is not mandatory here, you could simply define available_locales in your config/application.rb file
And as said in the comments, you should definitely accept some answers to improve your accept_rate

Locale fallback from country to language without having to define each individually

I am localizing an app with the default rails I18n with globalize3 as the back-end.
Is it possible to set a locale with a country code (ie :fr-CA) to fallback to its specific language (:fr) before going to the default fallback automatically? I know its possible to set each locale/country manually with
config.i18n.fallbacks = {'fr-CA' => 'fr'}
But it would be nice to not have to add each fallback manually and have this behaviour automatic.
To achieve precisely this I have an initializer with
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
See the source code for more info.
Edit:
This reminds me, there is an annoying bug in the ActionView LookupContext which prevents this from working for localized views (though it works correcly for locale files). I see it still hasn't been fixed. Basically, if you have any localized views (help pages for example, which are unsuitable to store in locale files due to their length) then a fr-CA locale will not fall back to a view called help.fr.html.erb. You either have to name the file help.fr-CA.html.erb or, which is what I have done, monkeypatch the LookupContext with another initializer, sort of like this:
module ActionView
class LookupContext
# Override locale= to also set the I18n.locale. If the current I18n.config object responds
# to original_config, it means that it's has a copy of the original I18n configuration and it's
# acting as proxy, which we need to skip.
def locale=(value)
if value
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
config.locale = value[0,2] # only use first part of the locale in lookups
end
super(#skip_default_locale ? I18n.locale : default_locale)
end
end
end
Another edit: Note that the patch is rather crude and breaks full locale lookups, going straight for just the language. If you need to also have fully matching views (language-REGION) you'll need to improve my code!

Resources