I'm trying to implement fallbacks for translated attributes using Globalize3 and I18n fallbacks. To get fallbacks up and running, I added to my environment.rb file:
#support for locale fallbacks
require "i18n/backend/fallbacks"
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
And then in my config file:
config.i18n.fallbacks = {'en-US' => 'zh-CN', 'zh-CN' => 'en-US'}
Now I have an app running where, if a field is not translated in the 'en-US' locale, it'll fall back on the 'zh-CN' locale, and vice versa.
However, this means that the fallback also occurs on forms on the site. This is undesired behaviour for two reasons:
Users might think that this means that this locale has this value for the input being seen (whereas it was inherited from the fallback locale).
Saving a form with these inherited values actually saves the translations as the current locale's values - so then all of a sudden you've got data on both locales, but the user may not know this (or know why).
I'd like to disable the fallbacks while on edit pages / in forms showing objects with translated attributes. Is there any way to do this?
I'm using versions of Globalize3 and I18n from svenfuchs https://github.com/svenfuchs/globalize3
Related
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.
I just updated to rails 4.0.2 and I'm getting this warning:
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
Is there any security issue in setting it to false?
Important: Make sure your app is not using I18n 0.6.8, it has a bug that prevents the configuration to be set correctly.
Short answer
In order to silence the warning edit the application.rb file and include the following line inside the Rails::Application body
config.i18n.enforce_available_locales = true
The possible values are:
false: if you
want to skip the locale validation
don't care about locales
true: if you
want the application to raise an error if an invalid locale is passed (or)
want to default to the new Rails behaviors (or)
care about locale validation
Note:
The old default behavior corresponds to false, not true.
If you are setting the config.i18n.default_locale configuration or other i18n settings, make sure to do it after setting the config.i18n.enforce_available_locales setting.
If your use third party gems that include I18n features, setting the variable through the Application config object, may not have an effect. In this case, set it directly to I18n using I18n.config.enforce_available_locales.
Caveats
Example
require File.expand_path('../boot', __FILE__)
# ...
module YouApplication
class Application < Rails::Application
# ...
config.i18n.enforce_available_locales = true
# or if one of your gem compete for pre-loading, use
I18n.config.enforce_available_locales = true
# ...
end
end
Long answer
The deprecation warning is now displayed both in Rails 4 (>= 4.0.2) and Rails 3.2 (>= 3.2.14). The reason is explained in this commit.
Enforce available locales
When I18n.config.enforce_available_locales is true we'll raise an
I18n::InvalidLocale exception if the passed locale is unavailable.
The default is set to nil which will display a deprecation error.
If set to false we'll skip enforcing available locales altogether (old behaviour).
This has been implemented in the following methods :
I18n.config.default_locale=
I18n.config.locale=
I18n.translate
I18n.localize
I18n.transliterate
Before this change, if you passed an unsupported locale, Rails would silently switch to it if the locale is valid (i.e. if there is a corresponding locale file in the /config/locales folder), otherwise the locale would default to the config.i18n.default_locale configuration (which defaults to :en).
The new version of the I18n gem, forces developers to be a little bit more conscious of the locale management.
In the future, the behavior will change and if a locale is invalid, the Rails app will raise an error.
In preparation of such change (that may potentially break several applications that until today were relying on silent defaults), the warning is forcing you to explicitly declare which validation you want to perform, during the current transition period.
To restore the previous behavior, simply set the following configuration to false
config.i18n.enforce_available_locales = false
otherwise, set it to true to match the new Rails defaults or if you want to be more rigid on domain validation and avoid switching to the default in case of invalid locale.
config.i18n.enforce_available_locales = true
Caveat
If you are setting the config.i18n.default_locale configuration or using any of the previously mentioned methods (default_locale=, locale=, translate, etc), make sure to do it after setting the config.i18n.enforce_available_locales setting. Otherwise, the deprecation warning will keep on popping up. (Thanks Fábio Batista).
If you use third party gems that include I18n features, setting the variable through may not have effect. In fact, the issue is the same as described in the previous point, just a little bit harder to debug.
This issue is a matter of precedence. When you set the config in your Rails app, the value is not immediately assigned to the I18n gem. Rails stores each config in an internal object, loads the dependencies (Railties and third party gems) and then it passes the configuration to the target classes. If you use a gem (or Rails plugin) that calls any of the I18n methods before the config is assigned to I18n, then you'll get the warning.
In this case, you need to skip the Rails stack and set the config immediately to the I18n gem by calling
I18n.config.enforce_available_locales = true
instead of
config.i18n.enforce_available_locales = true
The issue is easy to prove. Try to generate a new empty Rails app and you will see that setting config.i18n in the application.rb works fine.
If in your app it does not, there is an easy way to debug the culprit. Locate the i18n gem in your system, open the i18n.rb file and edit the method enforce_available_locales! to include the statement puts caller.inspect.
This will cause the method to print the stacktrace whenever invoked. You will be able to determine which gem is calling it by inspecting the stacktrace (in my case it was Authlogic).
["/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/i18n-0.6.9/lib/i18n.rb:150:in `translate'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/i18n/translator.rb:8:in `translate'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/i18n.rb:79:in `translate'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:68:in `validates_format_of_email_field_options'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:102:in `block in included'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:99:in `class_eval'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/email.rb:99:in `included'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `include'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `block in acts_as_authentic'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `each'",
"/Users/weppos/.rvm/gems/ruby-2.0.0-p247#application/gems/authlogic-3.1.0/lib/authlogic/acts_as_authentic/base.rb:37:in `acts_as_authentic'",
"/Users/weppos/Projects/application/app/models/user.rb:8:in `<class:User>'",
"/Users/weppos/Projects/application/app/models/user.rb:1:in `<top (required)>'",
Just for completeness, note that you can also get rid of the warning by setting I18n.enforce_available_locales to true (or false) in config/application.rb:
require File.expand_path('../boot', __FILE__)
.
.
.
module SampleApp
class Application < Rails::Application
.
.
.
I18n.enforce_available_locales = true
.
.
.
end
end
I18n.config.enforce_available_locales = true worked for me in Rails 3.2.16 (I put it in config/application.rb)
Doesn't seem that way - that'd be previous behavior of the way i18n works - new behavior (true) will raise an error when you ask for a locale not implemented/available.
See the commit that added this warning: https://github.com/svenfuchs/i18n/commit/3b6e56e06fd70f6e4507996b017238505e66608c
If you want to care about locales write into appilcation.rb file.
config.i18n.enforce_available_locales = true
You can write false if locale validation and do not care about that.
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.
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!
I18n fallback is loaded:
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
Any idea now to temporary disable it? I have forms, where I want to edit various language versions, and with fallback I am getting fields with default language, if given translation is yet not present.
You can pass the fallback: true option to I18n.t, which will prevent I18n from looking up other locales (see implementation here). But it's probably not part of the public API...
You can pass :fallback => 'false' on your I18n.translate calls, but this is not part of the public API.
Another way you might want to try is the following:
I18n.available_locales.each do
|al| I18n.fallbacks.merge!({al => [al]})
end
This will basically make the fallback for each available locale to include only itself. So, if the translation is not found in itself, then there is not fallback to fall back to.
However, then you need to find a way to restore to the default fallback.
You can do that for example with a statement like:
I18n.available_locales.each do
|al| I18n.fallbacks.merge!({al => [al, I18n.default_locale]})
end
if anyone is still wondering how to do that, you can change the I18n.fallbacks on the fly:
def foo
I18n.fallbacks[:at] = [:at]
# do stuff with I18n#t
ensure
I18n.fallbacks[:at] = [:at, :de] # or whatever is was before
end
Not sure how safe is that though.
Are you using globalize?
I'm using I18n fallback for my system strings, and globalize3 for my attribute translations. I want system strings to fallback, but not attributes. I simply disabled fallbacks for globalize only with a small monkey patch:
config/initializers/i18n.rb:
require "i18n/backend/fallbacks"
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
# monkey patch globalize3 to not use fallbacks
module Globalize
def self.fallbacks?
false
end
end