Skip to content

Commit

Permalink
Use Trans.translatable?/2 from Translator module
Browse files Browse the repository at this point in the history
  • Loading branch information
crbelaus committed Apr 2, 2017
1 parent d02711d commit c1c333f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 23 deletions.
32 changes: 11 additions & 21 deletions lib/trans/translator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -63,31 +63,21 @@ defmodule Trans.Translator do
@spec translate(struct, atom, atom) :: any
def translate(%{__struct__: module} = struct, locale, field)
when is_atom(locale) and is_atom(field) do
translatable_fields = get_translatable_fields(module)
raise_if_untranslatable(translatable_fields, field)

translated_field = with {:ok, all_translations} <- Map.fetch(struct, :translations),
{:ok, translations_for_locale} <- Map.fetch(all_translations, to_string(locale)),
{:ok, translated_field} <- Map.fetch(translations_for_locale, to_string(field)),
do: translated_field
case translated_field do
:error -> Map.fetch!(struct, field) # Fallback to the default value
_ -> translated_field # Return the translated value
unless Trans.translatable?(struct, field) do
raise "'#{inspect(module)}' module must declare '#{inspect(field)}' as translatable"
end
end

defp get_translatable_fields(module) do
if module.__info__(:functions)[:__trans__] do
module.__trans__(:fields)
else
raise "#{module} must use `Trans` in order to be translated"
# Return the translation or fall back to the default value
case translated_field(struct, locale, field) do
:error -> Map.fetch!(struct, field)
translation -> translation
end
end

defp raise_if_untranslatable(fields, field) do
unless Enum.member?(fields, field) do
raise "'#{field}' is not translatable. Translatable fields are #{inspect(fields)}"
end
defp translated_field(struct, locale, field) do
with {:ok, all_translations} <- Map.fetch(struct, :translations),
{:ok, translations_for_locale} <- Map.fetch(all_translations, to_string(locale)),
{:ok, translated_field} <- Map.fetch(translations_for_locale, to_string(field)),
do: translated_field
end

end
3 changes: 1 addition & 2 deletions test/translator_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ defmodule TranslatorTest do
end

test "raise error wen translating an untraslatable attribute" do
expected_message = "'fake_attr' is not translatable. Translatable fields are [:title, :body]"
assert_raise RuntimeError, expected_message, fn ->
assert_raise RuntimeError, "'Trans.Article' module must declare ':fake_attr' as translatable", fn ->
Translator.translate(build(:article), :es, :fake_attr)
end
end
Expand Down

0 comments on commit c1c333f

Please sign in to comment.