class BingTranslator
Attributes
api_client[R]
Public Class Methods
new(subscription_key, options = {})
click to toggle source
# File lib/bing_translator.rb, line 107 def initialize(subscription_key, options = {}) skip_ssl_verify = options.fetch(:skip_ssl_verify, false) read_timeout = options.fetch(:read_timeout, 60) open_timeout = options.fetch(:open_timeout, 60) @api_client = ApiClient.new(subscription_key, skip_ssl_verify, read_timeout, open_timeout) end
Public Instance Methods
detect(text)
click to toggle source
# File lib/bing_translator.rb, line 132 def detect(text) data = [{ 'Text' => text }].to_json response_json = api_client.post('/detect', data: data) best_detection = response_json.sort_by { |detection| -detection['score'] }.first best_detection['language'].to_sym end
language_names(codes, locale = 'en')
click to toggle source
# File lib/bing_translator.rb, line 151 def language_names(codes, locale = 'en') response_json = api_client.get('/languages', params: { scope: 'translation' }, headers: { 'Accept-Language' => locale }, authorization: false) codes.map do |code| response = response_json['translation'][code.to_s] response['name'] unless response.nil? end end
speak(text, params = {})
click to toggle source
# File lib/bing_translator.rb, line 140 def speak(text, params = {}) raise UsageException.new('Not supported since 3.0.0') end
supported_language_codes()
click to toggle source
# File lib/bing_translator.rb, line 144 def supported_language_codes response_json = api_client.get('/languages', params: { scope: 'translation' }, authorization: false) response_json['translation'].keys end
translate(text, params)
click to toggle source
# File lib/bing_translator.rb, line 114 def translate(text, params) translate_array([text], params).first end
translate_array(texts, params = {})
click to toggle source
# File lib/bing_translator.rb, line 118 def translate_array(texts, params = {}) translations = translation_request(texts, params) translations.map do |translation| translation['text'] if translation.is_a?(Hash) end end
translate_array2(texts, params = {})
click to toggle source
# File lib/bing_translator.rb, line 125 def translate_array2(texts, params = {}) translations = translation_request(texts, params.merge('includeAlignment' => true)) translations.map do |translation| [translation['text'], translation['alignment']['proj']] if translation.is_a?(Hash) end end
Private Instance Methods
translation_request(texts, params)
click to toggle source
# File lib/bing_translator.rb, line 166 def translation_request(texts, params) raise UsageException.new('Must provide :to.') if params[:to].nil? data = texts.map { |text| { 'Text' => text } }.to_json response_json = api_client.post('/translate', params: params, data: data) to_lang = params[:to].to_s response_json.map do |translation| # There should be just one translation, but who knows... translation['translations'].find { |result| result['to'].casecmp(to_lang).zero? } end end