My app has schemas with translatable fields.
defmodule Translation do
embedded_schema do
field :en, :string
field :fr, :string
field :de, :string
end
def translate(translation) do
locale = Gettext.get_locale(MyApp.Gettext)
#...
end
end
defmodule Project do
schema "projects" do
embeds_one :title, Translation
end
end
Now, instead of writing everywhere
<%= Translation.translate(project.title) %>
I used protocol:
defimpl Phoenix.HTML.Safe, for: Translation do
def to_iodata(translation) do
Phoenix.HTML.Safe.to_iodata(Translation.translate(translation))
end
end
which automagically translates texts in templates.
<%= project.title %>
This works so well that I got suspicious. Do you see disadvantages of this approach? Or better solution?