Module: EasyTranslate::Translation

Included in:
EasyTranslate
Defined in:
lib/easy_translate/translation.rb

Defined Under Namespace

Classes: TranslationRequest

Instance Method Summary collapse

Instance Method Details

#translate(texts, options = {}, http_options = {}) ⇒ String, Array

Translate text

Parameters:

  • texts (String, Array)
    • A single string or set of strings to translate

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :batch_size (Fixnum)
    • Maximum keys per request (optional, default 100)

  • :concurrency (Fixnum)
    • Maximum concurrent requests (optional, default 4)

  • :source (String, Symbol)
    • The source language (optional)

  • :target (String, Symbol)
    • The target language (required)

  • :html (Boolean)
    • Whether or not the supplied string is HTML (optional)

Returns:

  • (String, Array)

    Translated text or texts



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/easy_translate/translation.rb', line 19

def translate(texts, options = {}, http_options = {})
  options       = options.dup
  batch_size    = options.delete(:batch_size) || 100
  concurrency   = options.delete(:concurrency) || 4
  batches       = Array(texts).each_slice(batch_size).to_a
  if concurrency > 1 && batches.size > 1
    pool          = Thread::Pool.new([concurrency, 1 + (texts.length - 1) / batch_size].min)
    batch_results = ThreadSafe::Array.new
    batches.each_with_index do |texts_batch, i|
      pool.process { batch_results[i] = request_translations(texts_batch, options, http_options) }
    end
    pool.shutdown
    results = batch_results.reduce(:+)
  else
    results = batches.map { |texts_batch| request_translations(texts_batch, options, http_options) }.reduce(:+)
  end
  # if they only asked for one, only give one back
  texts.is_a?(String) ? results[0] : results
ensure
  pool.shutdown! if pool && !pool.shutdown?
end