diff --git a/README.md b/README.md index b64ffd0..84a269d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ by adding `localizator` to your list of dependencies in `mix.exs`: ```elixir def deps do [ - {:localizator, "~> 0.1.16"} + {:localizator, "~> 0.1.17"} ] end ``` diff --git a/lib/commons/commons.ex b/lib/commons/commons.ex index b36335b..0ce616d 100644 --- a/lib/commons/commons.ex +++ b/lib/commons/commons.ex @@ -5,6 +5,17 @@ defmodule Localizator.Commons do String.match?(string, @html_regex) end + def first_non_empty_longest_string(map) when is_map(map) do + map + |> Map.values() + |> Enum.reject(&is_nil(&1)) + |> Enum.filter(&is_binary(&1)) + |> Enum.map(&String.trim(&1)) + |> Enum.reject(&(&1 == "")) + |> Enum.sort(&(String.length(&1) >= String.length(&2))) + |> List.first() + end + def struct_from_map(a_map, as: a_struct) do # Find the keys within the map keys = diff --git a/lib/translator/microsoft.ex b/lib/translator/microsoft.ex index c3d87da..151e4a8 100644 --- a/lib/translator/microsoft.ex +++ b/lib/translator/microsoft.ex @@ -8,6 +8,8 @@ defmodule Localizator.Translator.Microsoft do @behaviour Localizator.Translator.Base + alias Localizator.Commons + @impl true @spec detect(nil) :: {:error, message} def detect(nil), do: {:error, "Couldn't detect language"} @@ -23,10 +25,7 @@ defmodule Localizator.Translator.Microsoft do @impl true @spec detect(map) :: {:ok, locale} | {:error, message} - def detect(map) when is_map(map) do - {:ok, sample} = Map.fetch(map, List.first(Map.keys(map))) - detect(sample) - end + def detect(map) when is_map(map), do: detect(Commons.first_non_empty_longest_string(map)) @impl true @spec translate(text, to, optional_from) :: {:ok, text} | {:error, message} diff --git a/lib/translator/yandex.ex b/lib/translator/yandex.ex index 089aa81..9948761 100644 --- a/lib/translator/yandex.ex +++ b/lib/translator/yandex.ex @@ -8,6 +8,8 @@ defmodule Localizator.Translator.Yandex do @behaviour Localizator.Translator.Base + alias Localizator.Commons + @impl true @spec detect(nil) :: {:error, message} def detect(nil), do: {:error, "Couldn't detect language"} @@ -23,10 +25,7 @@ defmodule Localizator.Translator.Yandex do @impl true @spec detect(map) :: {:ok, locale} | {:error, message} - def detect(map) when is_map(map) do - {:ok, sample} = Map.fetch(map, List.first(Map.keys(map))) - detect(sample) - end + def detect(map) when is_map(map), do: detect(Commons.first_non_empty_longest_string(map)) @impl true @spec translate(text, to, optional_from) :: {:ok, text} | {:error, message} diff --git a/mix.exs b/mix.exs index 6810418..bfebbb0 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Localizator.MixProject do def project do [ app: :localizator, - version: "0.1.16", + version: "0.1.17", elixir: "~> 1.10", start_permanent: Mix.env() == :prod, deps: deps()