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
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, = {}, = {}) = .dup batch_size = .delete(:batch_size) || 100 concurrency = .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, , ) } end pool.shutdown results = batch_results.reduce(:+) else results = batches.map { |texts_batch| request_translations(texts_batch, , ) }.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 |