I have a translate_field/2
macro that receives the current locale and a list of available locale/field mappings (this is a legacy database and we have some bizarre names for translation columns).
current_locale = "en"
query =
from t in Table,
select: %{
id: t.id,
description: translate_field(^current_locale, en: t.description_en, pt: t.descricao, es: t.description_es),
...
}
But I don’t know how to evaluate locale
parameter, so it obviously fail:
== Compilation error on file web/models/table.ex ==
** (ArgumentError) argument error
:erlang.binary_to_atom({:^, [line: 120], [{:current_locale, [line: 120], nil}]}, :utf8)
translate_field/2
definition:
defmacro translate_field(locale, field_map) do
quote do
unquote(Keyword.fetch!(field_map, String.to_atom(locale)))
end
end
If I call it with a hardcoded locale translate_field("en", en: t.description_en, pt: t.descricao, es: t.description_es)
it works as expected.
I tried other quote
/unquote
definition variations, but Ecto’s never happy with the returned AST.
So, what I’m doing wrong? How can I make this work?
If it’s not possible, any other approach I can follow to achieve this?