# `Localize.Translate`
[🔗](https://github.com/elixir-localize/localize_translate/blob/v0.5.0/lib/localize/translate.ex#L1)

Manage translations embedded into translation structs.

Although it can be used with any struct **`Localize.Translate` shines when paired with an
`Ecto.Schema`**. It allows you to keep the translations into a field of the schema and avoids
requiring extra tables for translation storage and complex _joins_ when retrieving translations
from the database.

The runtime API lives on `Localize.Translate` itself:

* `translate/1`, `translate/2` return a translated copy of an entire struct, or a single
  field when the second argument is a field name.

* `translate/3` and `translate!/3` return a single translated field with an explicit
  locale or locale fallback chain.

* `translatable?/2` reports whether a field is declared as translatable.

* `locale_id/1` validates a locale and returns the CLDR locale id translations are
  keyed by.

* `default_locale/1` resolves the locale of a struct's base fields, and `locale_chain/2`
  expands a locale into the CLDR fallback chain the reads walk, for code that builds its
  own lookups, such as a data-layer calculation.

For `Ecto.Query` support, `Localize.Translate.QueryBuilder` provides the `translated/4`
and `translated_as/4` macros (requires `Ecto.SQL`).

### Locale handling

`Localize.Translate` builds on [`:localize`](https://hex.pm/packages/localize) for
CLDR-aware locale handling. Three properties follow:

* **All locale inputs validate.** Atoms (`:en`), strings (`"en"`), and
  `%Localize.LanguageTag{}` structs are accepted anywhere a locale is expected — in
  `:locales`, `translate/N`, and `QueryBuilder.translated/4`. Each value is run
  through `Localize.validate_locale/1` and unwrapped to its `:cldr_locale_id` atom.
  An invalid locale never raises at runtime: `translate/2,3` and
  `QueryBuilder.translated/4` leave it out of the fallback chain, so it resolves to
  the next locale or the base value, and only `translate!/3` raises it. An invalid
  locale in the `:locales` option raises when the schema compiles.

* **Fallbacks walk the CLDR parent chain.** A locale expands into a fallback chain
  by walking parents (e.g. `:"en-AU"` → `:"en-001"` → `:en`, stopping before the
  `:und` root). For `QueryBuilder`, the chain is filtered to the locales declared in
  `:locales` so unsupported parents don't generate dead branches.

* **The current locale is `Localize.get_locale/0`.** `translate/1` and `translate/2`
  (with a field name) default the locale from `Localize.get_locale/0` and walk its
  parents.

Mixed `:locales` lists like `[:en, %Localize.LanguageTag{cldr_locale_id: :fr}]` are
supported. After validation each entry is reduced to an atom, deduplicated, and
sorted.

When used, `Localize.Translate` accepts the following options:

* `:translates` (required) - list of the fields that will be translated.

* `:locales` (optional) - the list of locales for which translations will be stored. Required
  if you use the `translations/1` macro to auto-generate the embedded schema. Locales are
  atoms (for example `:en`, `:"en-AU"`).

* `:default_locale` (optional) - declares the locale of the base untranslated columns. The
  fields in the main schema are considered to be in this locale, and no separate translation
  embed is generated for it. Either a locale, or a `{module, function, arguments}` tuple for
  a default known only at runtime, such as the language of the site a record belongs to. The
  function is called as `apply(module, function, [subject | arguments])` with the struct
  being translated, or `nil` for a query, and returns a locale or `nil`. See
  `default_locale/1`. With a function, every locale in `:locales` gets an embed, so keep the
  default locale's text in the base fields, not in the container.

* `:container` (optional) - the name of the field that holds the translations. Defaults to
  `:translations`.

### Structured translations

Structured translations are the preferred and recommended way of using `Localize.Translate`. To
use structured translations, use the `translations/1` macro when defining a schema. The
`translations/1` macro will define an embedded schema with the name being the parameter passed
to the `translations/1` macro. Within the `:translations` field that is generated, an
`embeds_one/2` call is added for each non-default locale in `:locales`. Here's an example
schema configuration:

    defmodule MyApp.Article do
      use Ecto.Schema
      use Localize.Translate,
        translates: [:title, :body],
        locales: [:en, :es, :fr],
        default_locale: :en

      schema "articles" do
        field :title, :string
        field :body, :string
        translations :translations
      end
    end

When expanded by the Elixir compiler, the example above will look like the following code. It
is provided here only as an example to show what the `translations/1` macro compiles to.

    defmodule MyApp.Article do
      use Ecto.Schema

      schema "articles" do
        field :title, :string
        field :body, :string

        embeds_one :translations, Translations, on_replace: :update, primary_key: false do
          embeds_one :es, MyApp.Article.Translations.Fields
          embeds_one :fr, MyApp.Article.Translations.Fields
        end
      end
    end

    defmodule MyApp.Article.Translations.Fields do
      use Ecto.Schema

      @primary_key false
      embedded_schema do
        field :title, :string
        field :body, :string
      end
    end

### Reflection

Any module that uses `Localize.Translate` will have an autogenerated `__trans__` function that
can be used for runtime introspection of the translation metadata. Code that builds a
translatable module some other way, such as a framework extension, generates it with
`reflection/1`.

* `__trans__(:fields)` - Returns the list of translatable fields.

* `__trans__(:container)` - Returns the name of the translation container.

* `__trans__(:locales)` - Returns the configured locales (or `nil` if not given).

* `__trans__(:default_locale)` - Returns the `:default_locale` option as given: a locale, a
  `{module, function, arguments}` tuple, or `nil`. `default_locale/1` resolves it. The fields
  in the main schema are considered to be in this locale.

* `__trans__(:associations)` - Returns the fields that hold related records, which
  `translate/2` translates too. For an Ecto schema these are its associations and
  embeds. A module that defines `__trans__/1` itself, such as one built by a data layer
  other than Ecto, answers with its own list.

# `field`

```elixir
@type field() :: atom()
```

A struct field as an atom.

# `locale`

```elixir
@type locale() :: atom() | String.t()
```

A locale identifier as an atom (for example `:en`, `:"en-AU"`) or a string.

# `locale_list`

```elixir
@type locale_list() :: locale() | [locale(), ...]
```

When translating or querying either a single locale or a list of locales can be provided.

A list of locales acts as a fallback chain: each locale is tried in order until a translation
is found.

# `translatable`

```elixir
@type translatable() :: struct()
```

A translatable struct that uses `Localize.Translate`.

# `default_locale`

```elixir
@spec default_locale(translatable() | module() | term()) :: atom() | nil
```

Returns the default locale of a translatable struct or module: the locale its base
fields are written in.

The schema's `:default_locale` option is either a locale or a `{module, function,
arguments}` tuple. A tuple is called as `apply(module, function, [subject | arguments])`,
where the subject is the struct, or `nil` when a module is given, as it is for a query.

### Arguments

* `translatable` is a struct that uses `Localize.Translate`, or a module that does.

### Returns

* The default locale as a CLDR locale id atom, such as `:en` or `:"fr-CA"`, or

* `nil` when the schema has no default locale, or its function returns `nil` or a value
  that is not a valid locale, or when `translatable` is not a struct or module that uses
  `Localize.Translate`. With no default locale every locale is looked up in the
  translation container, so the base fields must not also have an entry there.

### Examples

    iex> Localize.Translate.default_locale(%Localize.Translate.Comment{})
    :en

    iex> Localize.Translate.default_locale(Localize.Translate.Comment)
    :en

# `locale_chain`

```elixir
@spec locale_chain(locale_list() | struct() | nil, keyword()) :: [atom()]
```

Expands a locale, or a list of locales, into the CLDR fallback chain that
`translate/2,3` and `QueryBuilder.translated/4` walk.

Each locale is validated and followed up its CLDR parent chain, stopping before the root
(`:"en-AU"` → `:"en-001"` → `:en`). A list is expanded locale by locale and
deduplicated in order. A locale that is not valid, `nil` included, or that resolves to
the CLDR root `und` is left out, as the reads leave it out, so a locale taken from a
request is safe to pass.

### Arguments

* `locale_or_locales` is a locale (an atom, a string or a `Localize.LanguageTag`) or a
  list of them.

* `options` is a keyword list of options.

### Options

* `:supported` is a list of locale atoms to keep, such as a schema's
  `__trans__(:locales)`, dropping parents no translation is stored for. `nil` or an
  empty list, the default, keeps the whole chain.

* `:default_locale` is the locale of the base fields, kept in the chain when
  `:supported` filters it even if it is not listed, so a read of it still reaches
  the base fields. `translate/2,3` and `QueryBuilder.translated/4` filter the same
  way.

### Returns

* The chain as a list of CLDR locale id atoms, which is empty when no locale is valid.

### Examples

    iex> Localize.Translate.locale_chain("fr-CA")
    [:"fr-CA", :fr]

    iex> Localize.Translate.locale_chain([:"en-AU", :es])
    [:"en-AU", :"en-001", :en, :es]

    iex> Localize.Translate.locale_chain(["not a locale", :es])
    [:es]

    iex> Localize.Translate.locale_chain(:"en-AU", supported: [:en, :es])
    [:en]

    iex> Localize.Translate.locale_chain([:en, :es], supported: [:es, :fr], default_locale: :en)
    [:en, :es]

# `locale_id`

```elixir
@spec locale_id(locale() | Localize.LanguageTag.t() | nil) ::
  {:ok, atom()} | {:error, Exception.t()}
```

Validates a locale and returns its canonical CLDR locale id, the key translations are
stored and read under.

Atoms, strings and `Localize.LanguageTag` structs are accepted, and converge to the
same id: `"fr_CA"`, `:"fr-CA"` and `"fr-CA"` are all `:"fr-CA"`. A language's default
region is folded into the language, as CLDR keeps no data of its own for it, so
`"en-US"` is `:en`.

### Arguments

* `locale` is a locale: an atom, a string or a `Localize.LanguageTag`.

### Returns

* `{:ok, locale_id}` with the CLDR locale id as an atom, or

* `{:error, exception}` when `locale` is not a valid locale, is `nil` or empty, or is a
  language CLDR has no data for, which resolves to the root `und`. Every such
  language would share that one key, so none is accepted.

### Examples

    iex> Localize.Translate.locale_id("fr_CA")
    {:ok, :"fr-CA"}

    iex> Localize.Translate.locale_id("en-US")
    {:ok, :en}

    iex> {:error, %Localize.InvalidLocaleError{}} = Localize.Translate.locale_id("tlh")
    iex> {:error, %Localize.InvalidLocaleError{}} = Localize.Translate.locale_id(nil)

# `reflection`
*macro* 

Defines the `__trans__/1` reflection that makes a module translatable.

`use Localize.Translate` calls this for you. Call it directly only from code that
builds a translatable module some other way, such as a framework extension, so the
module answers every key `Localize.Translate` asks for, including any a later
release adds.

### Arguments

* `options` is a keyword list of options.

### Options

* `:fields` is the list of translatable fields. Required.

* `:container` is the field holding the translations. Defaults to `:translations`.

* `:locales` is the list of locale atoms translations may be stored for, or `nil`
  for any. Defaults to `nil`.

* `:default_locale` is the locale of the base fields: a locale, a `{module,
  function, arguments}` tuple, or `nil`. Defaults to `nil`. See `default_locale/1`.

* `:store` is the `Localize.Translate.Store` module. Defaults to
  `Localize.Translate.Store.Embedded`.

* `:store_options` is the keyword list of options passed to the store. Defaults to
  `[]`.

* `:associations` is the list of fields holding related records that `translate/2`
  translates too, or `:schema` for an Ecto schema's associations and embeds. Defaults
  to `:schema`, which is no fields for a module that is not an Ecto schema.

### Returns

* The quoted definitions of `__trans__/1`, answering `:fields`, `:container`,
  `:locales`, `:default_locale`, `:store`, `:store_options` and `:associations`. An
  option of the wrong shape raises an `ArgumentError` when the module compiles.

### Examples

    defmodule MyApp.Note do
      require Localize.Translate

      defstruct text: nil, translations: %{}

      Localize.Translate.reflection(fields: [:text], default_locale: :en)
    end

# `translatable?`

```elixir
@spec translatable?(module() | translatable(), String.t() | atom()) :: boolean()
```

Checks whether the given field is translatable or not.

A string field is compared with the declared field names as strings, so a field name
taken from a request never creates an atom.

### Arguments

* `module_or_translatable` is either a module that uses `Localize.Translate` or a struct of
  that module.

* `field` is the field name as an atom or string.

### Returns

* `true` if the given field is translatable.

* `false` if the given field is not translatable, if the module or struct does not use
  `Localize.Translate`, or if either argument is not a module or a field name.

### Examples

Assuming the Article schema defined in [Structured translations](#module-structured-translations).

    iex> Localize.Translate.translatable?(Article, :title)
    true

    iex> Localize.Translate.translatable?(Article, "title")
    true

    iex> article = %Article{}
    iex> Localize.Translate.translatable?(article, :not_existing)
    false

    iex> Localize.Translate.translatable?(Date, :day)
    false

# `translate`

```elixir
@spec translate(translatable()) :: translatable()
```

Translates a whole struct into the current locale.

Equivalent to `translate(translatable, locale)` with `locale` resolved from
`Localize.get_locale/0` when the optional `:localize` dependency is loaded, falling back
to the schema's `:default_locale` otherwise.

### Arguments

* `translatable` is a struct that uses `Localize.Translate`.

### Returns

* The translated struct. A value that is not a struct using `Localize.Translate` is
  returned unchanged.

### Examples

    iex> comment = %Localize.Translate.Comment{
    ...>   comment: "Hello",
    ...>   transcriptions: %{"fr" => %{"comment" => "Bonjour"}}
    ...> }
    iex> Localize.put_locale(:fr)
    iex> Localize.Translate.translate(comment).comment
    "Bonjour"

# `translate`

```elixir
@spec translate(translatable(), locale_list() | field() | struct()) ::
  translatable() | any()
```

Translates a whole struct (or a single field) into the given locale.

Returns the struct with every translatable field — and every translatable association or
embed — replaced by the value for the requested locale, falling back to the default
value when the locale has no entry. If the second argument is the name of a translatable
field, returns that single translated field using the current locale (see `translate/3`
for an explicit locale).

### Arguments

* `translatable` is a struct that uses `Localize.Translate`.

* `locale_or_field` is one of:

  * an atom or string locale (e.g. `:es`, `"fr"`),

  * a list of locales acting as a fallback chain,

  * a `%Localize.LanguageTag{}` — when the optional `:localize` dependency is loaded,
    expanded into a fallback chain by walking the CLDR parent chain, or

  * an atom field name — translates a single field using the current locale (see
    `translate/3`).

### Returns

* The translated struct, or the translated value of a single field. A locale that is
  not valid is left out of the chain, so the struct is returned untranslated when no
  valid locale is left. A field whose store returns `{:error, exception}` keeps its
  base value. A value that is not a struct is returned unchanged.

### Examples

    # Translate the entire article into Spanish
    Localize.Translate.translate(article, :es)

    # Fallback chain — Deutsch missing, Spanish wins
    Localize.Translate.translate(article, [:de, :es])

# `translate`

```elixir
@spec translate(translatable(), field() | String.t(), locale_list() | struct()) ::
  any()
```

Translates a single field into the given locale.

Looks up the field's translation in the given locale (or first match in a fallback
chain) and returns it. Returns the base value if no translation is available.

### Arguments

* `translatable` is a struct that uses `Localize.Translate`.

* `field` is the name of the translatable field as an atom or a string.

* `locale` is either a single locale or a list of locales acting as a fallback chain.

### Returns

* The translated value, or the value from the base column when no translation exists
  for any locale in the chain. The chain is filtered to the schema's `:locales`, with
  its default locale kept, as `QueryBuilder.translated/4` filters it, so a stored
  locale the schema does not list is not read. A `nil` translation counts as missing,
  so the chain moves on to its next locale. A locale that is not valid, including `nil`, is left out of the
  chain rather than raised on, so a locale taken from a request is safe to pass. A
  store that returns `{:error, exception}`, one that could not answer, stops the chain
  and the base value is returned; use `translate!/3` to have that raised.

* The base value of a field that is not declared translatable, or `nil` for a field the
  struct does not have or a value that is not a struct. A string field name never
  creates an atom.

### Examples

    # Spanish title
    Localize.Translate.translate(article, :title, :es)

    # Unknown locale falls back to the base column
    Localize.Translate.translate(article, :title, :de)

    # Fallback chain
    Localize.Translate.translate(article, :title, [:de, :es])

    # A field that is not translatable is its base value
    Localize.Translate.translate(article, :id, :es)

# `translate!`

```elixir
@spec translate!(translatable(), field() | String.t(), locale_list() | struct()) ::
  any()
```

Translates a single field into the given locale, raising if no translation is available.

Strict variant of `translate/3`. Where `translate/3` falls back to the base value when a
translation is missing, `translate!/3` raises so callers can distinguish "no
translation" from "translation equals the default".

### Arguments

* `translatable` is a struct that uses `Localize.Translate`.

* `field` is the name of the translatable field as an atom or a string.

* `locale` is either a single locale or a list of locales acting as a fallback chain.

### Returns

* The translated value.

* Raises a `RuntimeError` if no translation exists for any locale in the chain. A `nil`
  translation counts as missing.

* Raises the store's exception if the store returns `{:error, exception}`, one that
  could not answer, such as an unreachable translation service.

* Raises an `ArgumentError` if `translatable` is not a struct that uses
  `Localize.Translate` or `field` is not one of its translatable fields.

* Raises a `Localize.InvalidLocaleError` if any locale in the chain is not valid,
  including `nil`.

### Examples

    Localize.Translate.translate!(article, :title, :de)
    ** (RuntimeError) translation doesn't exist for field ':title' in locale :de

# `translations`
*macro* 

Defines the embedded translation container field on an `Ecto.Schema`.

Within an `Ecto.Schema` block, expands into an `embeds_one/3` declaration for the named
container field plus auto-generated `Translations` and `Translations.Fields` embedded
schemas — one `embeds_one` per non-default locale, each holding the translatable string
fields declared in `:translates`.

### Arguments

* `field_name` is the name of the container field on the parent schema, given as an atom
  (commonly `:translations`).

* `translation_module` (optional) is the alias name of the generated translation schema.
  Defaults to `Translations`. Pass an alias to use a different module name under the parent.

* `locales_or_options` (optional) is either an explicit list of locale atoms, or a keyword
  list of options. When omitted, the locales configured via the `:locales` option on
  `use Localize.Translate` are used.

### Options

* `:build_field_schema` — when `true` (the default), generates both the translation
  schema (`Translations`, or the `translation_module` given) and its inner `Fields`
  schema. When `false`, neither is generated: the container field still embeds the
  translation schema, so define it yourself with one `embeds_one` per non-default locale,
  pointing at a `Fields` schema of your own, which may carry extra fields such as an
  update timestamp.

* `:fields_module` — a per-locale embedded schema of your own, used in place of the
  generated `Fields` schema. The translation schema is still generated, with each
  non-default locale embedding this module. It must be an `Ecto.Schema` that defines
  every field in `:translates` as a `:string`, which is checked when the parent schema
  compiles, and it may define any other fields, such as an update timestamp or the name
  of the translator. It must be compiled before the parent schema, so it cannot be a
  module nested inside it. It cannot be combined with `build_field_schema: false`.

Any other option raises an `ArgumentError` when the schema compiles.

### Returns

* The quoted `embeds_one/3` declaration for the container field, together with the
  generated translation schema and, unless `:fields_module` or `build_field_schema: false`
  is given, its `Fields` schema. One embed is generated per locale, leaving out a literal
  `:default_locale`; with a function default every locale gets one, since the default is
  known only at runtime.

### Examples

    defmodule MyApp.Article do
      use Ecto.Schema
      use Localize.Translate,
        translates: [:title, :body],
        locales: [:en, :es, :fr],
        default_locale: :en

      schema "articles" do
        field :title, :string
        field :body, :string
        translations :translations
      end
    end

A per-locale schema of your own keeps state beside each locale's translations:

    defmodule MyApp.Article.TranslationFields do
      use Ecto.Schema

      @primary_key false
      embedded_schema do
        field :title, :string
        field :body, :string
        field :translated_by, :string
        field :machine_translated, :boolean, default: false
      end
    end

    defmodule MyApp.Article do
      use Ecto.Schema
      use Localize.Translate,
        translates: [:title, :body],
        locales: [:en, :es, :fr],
        default_locale: :en

      schema "articles" do
        field :title, :string
        field :body, :string
        translations :translations, Translations, fields_module: MyApp.Article.TranslationFields
      end
    end

`Localize.Translate.translate/3` and `Localize.Translate.QueryBuilder` read only the
fields in `:translates`. A query on a whole locale, `translated(Article, a, :es)`, reads
the locale's whole object, so a locale that holds only such state is not `NULL`.

# `translations`
*macro* 

Defines the embedded translation container field with explicit locales.

Four-arity form of `translations/3`. Use this when you want to override the configured
`:locales` option for a single schema, or to pass an options keyword list alongside an
explicit locale list.

### Arguments

* `field_name` is the name of the container field on the parent schema, as an atom.

* `translation_module` is the alias name of the generated translation schema.

* `locales` is the explicit list of locale atoms for which translation embeds are
  generated. A literal `:default_locale` is left out.

* `options` is a keyword list of options.

### Options

* `:build_field_schema` and `:fields_module`, as described for `translations/3`.

### Returns

* The quoted `embeds_one/3` declaration for the container field and the generated
  schemas, as for `translations/3`, with one embed per locale in `locales`.

### Examples

    defmodule MyApp.Article do
      use Ecto.Schema
      use Localize.Translate,
        translates: [:title, :body],
        locales: [:en, :es, :fr],
        default_locale: :en

      schema "articles" do
        field :title, :string
        field :body, :string

        # Only Spanish translations for this schema, whatever :locales says
        translations :translations, Translations, [:es], []
      end
    end

# `validate_translations`

```elixir
@spec validate_translations(Ecto.Changeset.t()) :: Ecto.Changeset.t()
```

Validates the translations a changeset leaves on its record, for an Ecto schema whose
base fields are in its default locale.

The base fields hold the default locale's text, so the translation container must
not hold it too: if it did, a query and `translate/3` could disagree about which to
read. With a literal `:default_locale` the generated `translations/1` schema has no
embed for it, but a `{module, function, arguments}` default is known only per record,
so every locale gets an embed and only a validation can keep the default locale's
entry empty. Call this from a changeset function.

The check runs when the container or the record's default locale changes, so a row
stored before the rule was enforced does not block unrelated updates.

### Arguments

* `changeset` is an `Ecto.Changeset` for a schema that uses `Localize.Translate`.

### Returns

* The changeset, with an error on the container field when the record's translations
  hold text for its default locale, or, for a map container, for a locale that is not
  valid or not in the schema's `:locales`. A changeset for a schema that does not use
  `Localize.Translate` is returned unchanged.

### Examples

    def changeset(article, params) do
      article
      |> cast(params, [:title, :body, :site_id])
      |> cast_embed(:translations)
      |> Localize.Translate.validate_translations()
    end

---

*Consult [api-reference.md](api-reference.md) for complete listing*
