Class: Lit::CloudTranslation::Providers::Yandex

Inherits:
Base
  • Object
show all
Defined in:
lib/lit/cloud_translation/providers/yandex.rb

Overview

Yandex Translate API provider for Lit translation suggestions.

Configuration:

require 'lit/cloud_translation/providers/yandex'

Lit::CloudTranslation.provider = Lit::CloudTranslation::Providers::Yandeex

# API key can be given via ENV['YANDEX_TRANSLATE_API_KEY'].
#
# Alternatively, it can be set programmatically after setting provider:

Lit::CloudTranslation.configure do |config|
  config.api_key = 'the_api_key'
end

Instance Attribute Summary

Attributes inherited from Base

#config

Instance Method Summary collapse

Methods inherited from Base

configure, #initialize, translate

Constructor Details

This class inherits a constructor from Lit::CloudTranslation::Providers::Base

Instance Method Details

#translate(text:, from: nil, to:, **opts) ⇒ Object

rubocop:disable Metrics/MethodLength, Metrics/LineLength



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lit/cloud_translation/providers/yandex.rb', line 23

def translate(text:, from: nil, to:, **opts) # rubocop:disable Metrics/MethodLength, Metrics/LineLength
  # puts "api key is: #{config.api_key}"
  # puts "translating #{text} from #{from} to #{to}"
  uri = URI('https://translate.yandex.net/api/v1.5/tr.json/translate')
  params = {
    key: config.api_key,
    text: sanitize_text(text),
    lang: [from, to].compact.join('-'),
    format: opts[:format],
    options: opts[:options]
  }.compact
  uri.query = URI.encode_www_form(params)
  res = Net::HTTP.get_response(uri)

  unsanitize_text(
    case res
    when Net::HTTPOK
      translations = JSON.parse(res.body)['text']
      translations.size == 1 ? translations.first : translations
    else
      raise ::Lit::CloudTranslation::TranslationError,
            (JSON.parse(res.body)['message'] rescue "Unknown error: #{res.body}") # rubocop:disable Style/RescueModifier, Metrics/LineLength
    end
  )
end