Loading translations

Defining translations in HOCON files

For each language a separate file must be created in the resources folder and the name of the Locale as filename. It is recommended to create a subdirectory for your language files, in the examples below we picked babel.

en.conf
sourcegreeting = "Good afternoon"
de.conf
sourcegreeting = "Guten Tag"
de-AT.conf
sourcegreeting = "Grüß Gott"

Loading translations into a Babel

import cats.effect._
import cats.effect.unsafe.implicits.global
import io.taig.babel._

val babels = Loader.default[IO]
  .load("babel", Set(Locales.en, Locales.de, Locales.de_AT))
  .unsafeRunSync()
// babels: Translations[Babel] = Translations(Map(en -> Object(Map(greeting -> Value(Good afternoon))), de -> Object(Map(greeting -> Value(Guten Tag))), de-AT -> Object(Map(greeting -> Value(Grüß Gott)))))

Decoding the Babel into a data class

import cats.syntax.all._
import io.taig.babel.generic.auto._

final case class I18n(greeting: String)

object I18n {
  implicit val decoder: Decoder[I18n] = deriveDecoder[I18n]
}

val i18ns = IO.fromEither(Decoder[I18n].decodeAll(babels))
  .map(_.withFallback(Locales.en))
  .flatMap(_.liftTo[IO](new IllegalStateException("Translations for en missing")))
  .unsafeRunSync()
// i18ns: NonEmptyTranslations[I18n] = NonEmptyTranslations(en -> I18n(Good afternoon),Translations(Map(de -> I18n(Guten Tag), de-AT -> I18n(Grüß Gott))))
i18ns(Locales.de).greeting
// res0: String = "Guten Tag"
i18ns(Locales.de_AT).greeting
// res1: String = "Grüß Gott"
i18ns(Locales.de_CH).greeting
// res2: String = "Guten Tag"
i18ns(Locales.fr).greeting
// res3: String = "Good afternoon"