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.
Related
I've just updated to Rails 4.0.2 and I got the deprecation 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.
To get rid of the warning, I decided to set:
I18n.config.enforce_available_locales = true
in my config/application.rb file.
It worked pretty well on Development, all tests passed, and I was happy... Then I deployed my work in a staging server and it crashed!
Devise is looking for a locale :pt. All I have is a locale :pt-BR. I set it in my application.rb:
config.i18n.default_locale = 'pt-BR'
I don't know why devise is looking for :pt only. My locales in the config folder are: pt-BR.yml and devise.pt-BR.yml.
I tried to change the file name from devise.pt-BR.yml to devise.pt.yml (and inside from pt-BR to pt) and it worked.
I had to go back and set:
I18n.config.enforce_available_locales = false
to make it work.
I have two questions:
1 - Why this is not happening on the tests and on development?
2 - Why Devise is asking for :pt, if I'm setting the default locale as :pt-BR in my config?
Thanks in advance
Add devise-i18n to your Gemfile to get the pt-BR locale file for the Devise strings. This fixes the production problem.
As for why you're not seeing the issue in development, it may be because you're not triggering the specific I18n.t lookup - you need to narrow it down. Some Devise string is triggering this, and I suspect it won't cause an error until that string gets looked up. You need to narrow down the exact set of actions that causes the issue. If it's failing on startup, there might be some production eager loading going on that triggers the issue.
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!
Rails somehow mixes my locales an I have absolutely no clue why. Most of my translated strings work as expected, but for some it mixes the locales.
Interestingly, this only happens on one of our systems. Specifically running Passenger with Apache.
When using Webrick, Thin, or Passenger Standalone on my development system everything is alright.
This is what I have in my application.rb:
config.i18n.default_locale = :de
This is in application_controller.rb:
before_filter :set_locale
def set_locale
I18n.locale = #current_client ? #current_client.locale : I18n.default_locale
end
(I experience the problems on pages where #current_client is nil and the else part gets executed).
So, I am basically using the :de locale. When showing a validation error on a form, I experience mixed up translations like this:
ist zu kurz (nicht weniger als 6 Zeichen) und translation missing: en.activerecord.errors.custom.password_format
As you can see, the error message from the first failing validation is translated as expected, for the second error message tries to access the English translation (which does not exist).
I suspect a problem with lazy loading of translated strings even before the before_filter gets executed.
Any clues why this might happen?
For the record: This is Rails 3
EDIT:
I just discovered that this depends on the environment used. When using the development environment, everything is fine. When using the production environment (or a production-like) environment, I experience the behavior described above.
EDIT 2:
I found out even more: It specifically depends on config.cache_classes. When set to true, I see the mixed translations. When set to false (as in the typical development environment), i18n works as expected.
EDIT 3:
Maybe this is related to the following bug?
https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/5522
Edit 4:
This IS related to the bug mentioned above, the problem is due to eagerly loaded model classes, which use I18n strings, but eager class loading happens before I18n initialization, hence the translations are not found. There even is another bug about this:
https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/6353
Unfortunately, the Rails guys did not manage to include the fix in the recent 3.0.4 release (as far as I can tell). Hence I'm trying to figure out a workaround like this (in my application configuration):
config.before_eager_load do
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'de.yml').to_s]
I18n::Railtie.reloader.paths.concat I18n.load_path
I18n::Railtie.reloader.execute_if_updated
I18n.reload!
end
Unlucky, this does not work. Any clues?
This problem may also occours in case you have a Gem that also uses I18n (I was having this problem with active_admin). Rails sets I18n to late for the Gem to be able to use that same load_paths.
What I have done was to add this to production.rb:
config.before_configuration do
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
I18n.locale = 'pt-PT'
I18n.reload!
end
Here is my final workaround, which seems to work (put this in application.rb or one of your environment configuration files, as needed):
# THIS IS A WORKAROUND FOR A I18N BUG IN RAILS!
# Only required when cache_classes is set to true
# See https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/6353
config.before_eager_load do
I18n.locale = :de
I18n.load_path += Dir[Rails.root.join('config', 'locales', 'de.yml').to_s]
I18n.reload!
end
Hope this is useful to anybody else...
EDIT:
If this does not work for you, try before_configuration instead of before_eager_load (see solution below). At least, works again as workaround for me in Rails 3.0.10
Have you tried fiddling with the Passenger spawn method settings? Try to set it to Conservative, this way Passenger should behave the same as Thin.
Upgrading to rails 3.0.5 should fix this and similar I18n problems.
See: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/6353
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
I have a rails application that patches ActiveRecord with a hand-coded validator.
The patch is made by adding the following lines in config/environment.rb
Rails::Initializer.run do |config|
...
end
class ActiveRecord::Base
include MtLib::DBValidations
end
This works fine in production mode i.e. with
config.cache_classes = true
however it does not work in development with cache_classes set to false.
The error thrown is
ArgumentError (A copy of MtLib::DBValidations has been removed from
the module tree but is still active!):
My question is what is the process that is followed when cache_class is set to false. Does Rails re-run any of the initialization methods? If not then where is the best place for me to put my patch to ensure that it is in all models and survives a classes reload?
I have tried adding the patch to config/initializers/active_record_patch, however this is not re-run when the classes are reloaded.
The solution to this, provided by Frederick Cheung on the Ruby On Rails google group add the directory containing the loaded class into the load_once_path array.
I edited environment.rb to look like this
config.load_paths +=
%W( #{RAILS_ROOT}/lib/soap_clients/carefone #{RAILS_ROOT}/lib/mt_lib)
# Make sure load_once_paths is a subset of load_paths
config.load_once_paths += %W( #{RAILS_ROOT}/lib/mt_lib)
And now this works in development mode without having to reload the server on every request