Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing the locale from variables #46

Merged
merged 1 commit into from Sep 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 3 additions & 7 deletions lib/trans/query_builder.ex
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
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