diff --git a/lib/trans/query_builder.ex b/lib/trans/query_builder.ex index 5055e3d..9e2d719 100644 --- a/lib/trans/query_builder.ex +++ b/lib/trans/query_builder.ex @@ -82,27 +82,23 @@ if Code.ensure_loaded?(Ecto.Query) do with field <- field(translatable) do with {module_name, []} <- Module.eval_quoted(__CALLER__, module) do validate_field(module_name, field) - generate_query(schema(translatable), module_name, field, locale(locale)) + generate_query(schema(translatable), module_name, field, locale) end end end defp generate_query(schema, module, nil, locale) do quote do - fragment("(?->?)", field(unquote(schema), unquote(module.__trans__(:container))), ^unquote(locale)) + fragment("(?->?)", field(unquote(schema), unquote(module.__trans__(:container))), ^to_string(unquote(locale))) end end defp generate_query(schema, module, field, locale) do quote do - fragment("(?->?->>?)", field(unquote(schema), unquote(module.__trans__(:container))), ^unquote(locale), ^unquote(field)) + fragment("(?->?->>?)", field(unquote(schema), unquote(module.__trans__(:container))), ^to_string(unquote(locale)), ^unquote(field)) end end - defp locale(locale) when is_atom(locale) and not is_nil(locale), do: to_string(locale) - defp locale(locale) when is_binary(locale), do: locale - defp locale(_), do: raise ArgumentError, message: "The locale code must be either an atom or a string" - defp schema({{:., _, [schema, _field]}, _metadata, _args}), do: schema defp schema(schema), do: schema diff --git a/test/query_builder_test.exs b/test/query_builder_test.exs index e9cfbd1..4adcf14 100644 --- a/test/query_builder_test.exs +++ b/test/query_builder_test.exs @@ -148,21 +148,10 @@ defmodule QueryBuilderTest do fn -> Code.eval_quoted(invalid_module) end end - test "should raise when an invalid locale is specified" do - invalid_module = quote do - defmodule TestWrongQuery do - require Ecto.Query - import Ecto.Query, only: [from: 2] - - def invalid_query do - from a in Article, - where: not is_nil(translated(Article, a.title, nil)) - end - end - end - - assert_raise ArgumentError, - "The locale code must be either an atom or a string", - fn -> Code.eval_quoted(invalid_module) end + test "should allow passing the locale from a variable" do + locale = :es + articles = Repo.all(from a in Article, + order_by: translated(Article, a.title, locale)) + assert Enum.any?(articles) end end