View Source EctoI18n (ecto_i18n v0.4.1)
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 - using a column of :map
type for storing all the related localized data.
With this strategy, it can:
- avoid using extra tables for storing localized data.
- avoid using complex JOINs when retrieving localized data.
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 data in it:
defmodule MyApp.Repo.Migrations.AddLocalesToProducts do
use Ecto.Migration
def change do
alter table(:products) do
add :name_i18n, :map, null: false
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, locales: ["en", "zh-Hans"]
schema "products" do
field :sku, :string
field_i18n :name, :string
end
end
If you're curious about the underlying implementation here, you can read
EctoI18n.Schema
to learn more.
Next, you can use the extensions provided by EctoI18n
to
work with the localized schema, such as:
Summary
Functions
Checks whether a module or a struct has i18n support.
Returns supported locales of a struct or the underlying module.
Localizes a struct with given locale recursively.
Types
Functions
Checks whether a module or a struct has i18n support.
Examples
iex> EctoI18n.localizable?(Product)
iex> EctoI18n.localizable?(%Product{})
Returns supported locales of a struct or the underlying module.
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")