Skip to content

Commit

Permalink
Merge pull request #46 from belaustegui/issues-45-locale-as-variable
Browse files Browse the repository at this point in the history
Allow passing the locale from variables
  • Loading branch information
crbelaus committed Sep 29, 2017
2 parents 80d31a5 + 558e83c commit 7494d74
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 23 deletions.
10 changes: 3 additions & 7 deletions lib/trans/query_builder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 5 additions & 16 deletions test/query_builder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 7494d74

Please sign in to comment.