I have a simple question. Let’s assume I’m configuring a i18n
gem. It has simple configs like:
I18n.load_path += Dir[File.expand_path("config/locales") + "/*.yml"]
I18n.default_locale = :en
What is the ideal place to put it?
I have a simple question. Let’s assume I’m configuring a i18n
gem. It has simple configs like:
I18n.load_path += Dir[File.expand_path("config/locales") + "/*.yml"]
I18n.default_locale = :en
What is the ideal place to put it?
As far as I understand it a provider would be a good solution for that.
(V2.2: Providers | Hanami Guides)
Yes, providers are for this exactly
One thing I have liked to do with an i18n provide is not only configure it, but also register a component that allows an i18n interface to be auto-injected. Something like this:
# frozen_string_literal: true
Hanami.app.register_provider :i18n do
prepare do
require "i18n"
end
start do
# Your config here...
I18n.load_path += Dir[File.expand_path("config/locales") + "/*.yml"]
I18n.default_locale = :en
# Now register a component that can be used as a dependency. You have a couple of options here..
# (1) Register the whole I18n interface.
register "i18n", I18n
# This is just a little bit of sugar that allows you to do this:
#
# class MyClass
# include Deps["i18n"]
#
# def some_method
# i18n.t("some_key")
# end
# end
# (2) Alternatively, register a callable object that does translation only. This is a leaner
# interface that would feel "safer" for your various objects to use.
register "i18n.t", I18n.method(:t)
# Then you can do this:
#
# class MyClass
# include Deps["i18n.t"]
#
# def some_method
# t.call("some_key")
# # or
# t["some_key]
# end
# end
end
end
One thing I’d like to do in a not-too-distant next version of Hanami is to include zero-config i18n support out of the box. It would probably take the form of some sensible default config, conventional locations for translation files, and then a provider that does something like the above.
Definitely interested in your feedback on what would make a nice i18n experience
And in the meantime, let us know how you go with setting up your app!