I followed the great Rails guide on engines ( https://guides.rubyonrails.org/engines.html ) and managed to get my engine working in a host app.
However, the engine is loading only the en.yml
locale, even tough the host application has I18n.default_locale
and I18n.locale
both set to pt-br
, and I have a config/locales/pt-br.yml
file in my engine.
The guide only states that "For locales, simply place the locale files in the config/locales directory, just like you would in an application.", but apparently I need to do something else.
How would I make the engine to load the correct I18n locale files, based on the host app settings? If that's not possible, how the host app could set this locale in an initializer file, like a config option?
I managed to solve it. The key is to remember that I18n.locale
is a setting that should be set on every request.
So on my engine entry point ( lib/cron_monitor.rb
), I defined a setting:
module CronMonitor
class << self
attr_accessor :i18n
end
self.i18n = I18n.default_locale
Then in my engine's ApplicationController
, following Rails i18n documentation :
module CronMonitor
class ApplicationController < ActionController::Base
around_action :switch_locale
private
def switch_locale(&action)
locale = CronMonitor.i18n || I18n.default_locale
I18n.with_locale(locale, &action)
end
end
end
Also, if you have code in models or service objects that you also want to be translated, you should use I18n as well. Example:
module CronMonitor
class Category < ApplicationRecord
def self.some_method
message = I18n.translate(
"cron_monitor.starting_or_finishing.failure",
title: self.title,
locale: CronMonitor.i18n
)
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.