Class: Glossync::MissingTranslationHandler::GoogleTranslate

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

Overview

This handler attempts to translate the given string to the target language using the Google Translate API

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ GoogleTranslate

Returns a new instance of GoogleTranslate.

Parameters:

  • key

    the key for the Google Translate API



31
32
33
34
# File 'lib/glossync/missing_translation_handler.rb', line 31

def initialize(key)
  @api_key = key
  @cache = {}
end

Instance Method Details

#handle(_, who, field, locale) ⇒ Object

:nodoc:



52
53
54
55
56
57
58
# File 'lib/glossync/missing_translation_handler.rb', line 52

def handle(_, who, field, locale)
  key = who.tl_key(field)

  @cache[key] = translate(who[field], locale) unless @cache.key?(key)

  @cache[key]
end

#translate(text, to) ⇒ String

Translate text to the to locale

Parameters:

  • text

    the text to translate

  • to

    the locale to translate to

Returns:

  • (String)

    the translated text or an error message



40
41
42
43
44
45
46
47
48
49
# File 'lib/glossync/missing_translation_handler.rb', line 40

def translate(text, to)
  EasyTranslate.translate(
    text,
    from: Glossync.options[:base_locale],
    to: to,
    key: @api_key
  )
rescue SocketError
  "failed to connect to google translate api"
end