From 90df1faf076d4003ed879a7f01ef099c8b91d981 Mon Sep 17 00:00:00 2001 From: taitus Date: Fri, 25 Jan 2019 14:15:31 +0100 Subject: [PATCH] Maganement of available locales in MicrosoftTranslateClient - Create remote_available_locales method to recover available locales from microsoft tanslate client. This method will be useful to display the translation button as long as the locale sent is valid. - Create parse_locale method: Need parse available locales in Consul to will be valid on Microsoft Translate Client --- lib/microsoft_translate_client.rb | 1 + lib/remote_available_locales.rb | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 lib/remote_available_locales.rb diff --git a/lib/microsoft_translate_client.rb b/lib/microsoft_translate_client.rb index 23b595403..45c8845c8 100644 --- a/lib/microsoft_translate_client.rb +++ b/lib/microsoft_translate_client.rb @@ -1,5 +1,6 @@ require "translator-text" include SentencesParser +include RemoteAvailableLocales class MicrosoftTranslateClient CHARACTERS_LIMIT_PER_REQUEST = 5000 diff --git a/lib/remote_available_locales.rb b/lib/remote_available_locales.rb new file mode 100644 index 000000000..a7e66437a --- /dev/null +++ b/lib/remote_available_locales.rb @@ -0,0 +1,45 @@ +require "net/https" +require "uri" +require "cgi" +require "json" + +module RemoteAvailableLocales + + def load_remote_locales + remote_available_locales.map { |locale| locale.first } + end + + def parse_locale(locale) + case locale + when :"pt-BR" + :pt + when :"zh-CN" + :"zh-Hans" + when :"zh-TW" + :"zh-Hant" + else + locale + end + end + + private + + def remote_available_locales + host = "https://api.cognitive.microsofttranslator.com" + path = "/languages?api-version=3.0" + + uri = URI (host + path) + + request = Net::HTTP::Get.new(uri) + request["Ocp-Apim-Subscription-Key"] = Rails.application.secrets.microsoft_api_key + + response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == "https") do |http| + http.request (request) + end + + result = response.body.force_encoding("utf-8") + + JSON.parse(result)["translation"] + end + +end