Class: BetterTranslate::Strategies::BatchStrategy

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/better_translate/strategies/batch_strategy.rb

Overview

Batch translation strategy

Translates strings in batches for improved performance. Used for larger files (>= 50 strings).

Examples:

strategy = BatchStrategy.new(config, provider, tracker)
translated = strategy.translate(strings, "it", "Italian")

Constant Summary collapse

BATCH_SIZE =

Batch size for translation

10

Instance Attribute Summary

Attributes inherited from BaseStrategy

#config, #progress_tracker, #provider

Instance Method Summary collapse

Methods inherited from BaseStrategy

#initialize

Constructor Details

This class inherits a constructor from BetterTranslate::Strategies::BaseStrategy

Instance Method Details

#translate(strings, target_lang_code, target_lang_name) ⇒ Hash

Translate strings in batches

Examples:

strings = { "key1" => "value1", "key2" => "value2", ... }
translated = strategy.translate(strings, "it", "Italian")

Parameters:

  • strings (Hash)

    Flattened hash of strings to translate

  • target_lang_code (String)

    Target language code

  • target_lang_name (String)

    Target language name

Returns:

  • (Hash)

    Translated strings (flattened)



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/better_translate/strategies/batch_strategy.rb', line 29

def translate(strings, target_lang_code, target_lang_name)
  # @type var translated: Hash[String, String]
  translated = {}
  keys = strings.keys
  values = strings.values
  total_batches = (values.size.to_f / BATCH_SIZE).ceil

  values.each_slice(BATCH_SIZE).with_index do |batch, batch_index|
    progress_tracker.update(
      language: target_lang_name,
      current_key: "Batch #{batch_index + 1}/#{total_batches}",
      progress: ((batch_index + 1).to_f / total_batches * 100.0).round(1).to_f
    )

    translated_batch = provider.translate_batch(batch, target_lang_code, target_lang_name)

    # Map back to keys
    batch_keys = keys[batch_index * BATCH_SIZE, batch.size]
    batch_keys&.each_with_index do |key, i|
      translated[key] = translated_batch[i]
    end
  end

  translated
end