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
This commit is contained in:
taitus
2019-01-25 14:15:31 +01:00
committed by voodoorai2000
parent 31011033a7
commit 90df1faf07
2 changed files with 46 additions and 0 deletions

View File

@@ -1,5 +1,6 @@
require "translator-text"
include SentencesParser
include RemoteAvailableLocales
class MicrosoftTranslateClient
CHARACTERS_LIMIT_PER_REQUEST = 5000

View File

@@ -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