View Source EctoI18n (ecto_i18n v0.3.0)
Provides i18n support for Ecto.
Preface
There're lots of strategies to localize contents in database
(archived).
For now, EctoI18n
implements only strategy 6 mentioned
above - creating an extra column for storing all the localized contents
for that table.
With this strategy, it can:
- avoid using extra tables for storing localized contents.
- avoid using complex JOINs when retrieving localized contents.
Maybe other strategies will be implemented later, but for now, I only need this one.
Quick start
Let's say that we have a schema which needs to be localized:
defmodule MyApp.Shop.Product do
use Ecto.Schema
schema "products" do
field :sku, :string
field :name, :string
end
end
The first step is to add a new column to the table at database level, so we can store localized contents in it:
defmodule MyApp.Repo.Migrations.AddLocalesToProducts do
use Ecto.Migration
def change do
alter table(:products) do
add :locales, :map
end
end
end
The second step is to update schema for using the new column:
defmodule MyApp.Shop.Product do
use Ecto.Schema
use EctoI18n.Schema, default_locale: "en", locales: ["zh-Hans", "zh-Hant"]
schema "products" do
field :sku, :string
field :name, :string
locales :locales do
field :name, :string
end
end
end
If you're curious about the underlying implementation here, you can read
EctoI18n.Schema.locales/2
to learn more.
Next, you can use the extensions provided by EctoI18n
to
work with the localized schema, such as:
EctoI18n.localize!/2
EctoI18n.Changeset.cast_locales/3
EctoI18n.Query
(Still in planning)- ...
Summary
Functions
Ensures that a module or a struct is localizable. Or, an error is raised.
Checks whether a module or a struct is localizable.
Checks whether a field in a module or a struct is localizable.
Localizes a struct with given locale recursively.
Types
Functions
Ensures that a module or a struct is localizable. Or, an error is raised.
Checks whether a module or a struct is localizable.
Examples
iex> EctoI18n.localizable?(Product)
iex> EctoI18n.localizable?(%Product{})
Checks whether a field in a module or a struct is localizable.
Examples
iex> Ecto.localizable?(Product, :name)
iex> Ecto.localizable?(%Product{}, :name)
Localizes a struct with given locale recursively.
All localizable values in the struct will be localized into the give locale.
Examples
iex> EctoI18n.localize!(product, "zh-Hans")