Last active
July 1, 2017 00:02
-
-
Save nicolasblanco/75cd1f3b67010d95ac8a29956b9649ab to your computer and use it in GitHub Desktop.
Translation Fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule TranslationFields do | |
| @moduledoc """ | |
| Usage: | |
| defmodule Product do | |
| use TranslationFields | |
| @translated_locales ~w(en fr) | |
| @translated_fields ~w(name description) | |
| schema "products" do | |
| field :price, :integer | |
| field :sku, :string | |
| field :slug, :string | |
| translation_fields() | |
| timestamps() | |
| end | |
| Then for each `@translated_fields` it will define one persistent field containing the translations | |
| as a map (named `fieldname_translations`), and virtual attributes for each locale (named `fieldname_localename`). | |
| ie.: `%Product{description_en: nil, description_fr: nil, description_translations: nil, name_en: nil, name_fr: nil, name_translations: nil, ...} | |
| """ | |
| defmacro __using__(_opts) do | |
| quote do | |
| import TranslationFields | |
| @translated_locales ~w() | |
| @translated_fields ~w() | |
| end | |
| end | |
| defmacro translation_fields do | |
| quote do | |
| Enum.each(@translated_fields, fn(field) -> | |
| field :"#{field}_translations", :map | |
| Enum.each(@translated_locales, fn(locale) -> | |
| field :"#{field}_#{locale}", :string, virtual: true | |
| end) | |
| end) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment