Class: BingTranslator

Inherits:
Object
  • Object
show all
Defined in:
lib/bing_translator.rb

Defined Under Namespace

Classes: ApiClient, Exception

Instance Method Summary collapse

Constructor Details

#initialize(subscription_key, options = {}) ⇒ BingTranslator

Returns a new instance of BingTranslator.



98
99
100
101
# File 'lib/bing_translator.rb', line 98

def initialize(subscription_key, options = {})
  skip_ssl_verify = options.fetch(:skip_ssl_verify, false)
  @api_client = ApiClient.new(subscription_key, skip_ssl_verify)
end

Instance Method Details

#detect(text) ⇒ Object



121
122
123
124
125
126
127
# File 'lib/bing_translator.rb', line 121

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') ⇒ Object



140
141
142
143
144
145
146
147
148
149
# File 'lib/bing_translator.rb', line 140

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 = {}) ⇒ Object

Raises:



129
130
131
# File 'lib/bing_translator.rb', line 129

def speak(text, params = {})
  raise Exception.new('Not supported since 3.0.0')
end

#supported_language_codesObject



133
134
135
136
137
138
# File 'lib/bing_translator.rb', line 133

def supported_language_codes
  response_json = api_client.get('/languages',
                                 params: { scope: 'translation' },
                                 authorization: false)
  response_json['translation'].keys
end

#translate(text, params) ⇒ Object



103
104
105
# File 'lib/bing_translator.rb', line 103

def translate(text, params)
  translate_array([text], params).first
end

#translate_array(texts, params = {}) ⇒ Object



107
108
109
110
111
112
# File 'lib/bing_translator.rb', line 107

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 = {}) ⇒ Object



114
115
116
117
118
119
# File 'lib/bing_translator.rb', line 114

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