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:
@@ -1,5 +1,6 @@
|
||||
require "translator-text"
|
||||
include SentencesParser
|
||||
include RemoteAvailableLocales
|
||||
|
||||
class MicrosoftTranslateClient
|
||||
CHARACTERS_LIMIT_PER_REQUEST = 5000
|
||||
|
||||
45
lib/remote_available_locales.rb
Normal file
45
lib/remote_available_locales.rb
Normal 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
|
||||
Reference in New Issue
Block a user