Class: Translatomatic::Translator

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/translatomatic/translator.rb

Overview

Translates strings from one language to another

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Translator

Returns a new instance of Translator.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/translatomatic/translator.rb', line 6

def initialize(options = {})
  @listener = options[:listener]
  @providers = resolve_providers(options)
  raise t('translator.provider_required') if @providers.empty?
  @providers.each { |i| i.listener = @listener } if @listener

  # use database by default if we're connected to a database
  @use_db = !options[:no_database] && ActiveRecord::Base.connected?
  log.debug(t('translator.database_disabled')) unless @use_db

  @stats = Translatomatic::Translation::Stats.new
end

Instance Attribute Details

#statsObject (readonly)

Returns the value of attribute stats.



4
5
6
# File 'lib/translatomatic/translator.rb', line 4

def stats
  @stats
end

Instance Method Details

#translate(texts, to_locales) ⇒ Array<Translatomatic::Translation>

Translate texts to a target locale

Parameters:

Returns:



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
48
49
50
51
# File 'lib/translatomatic/translator.rb', line 23

def translate(texts, to_locales)
  text_collection = TextCollection.new(texts)
  to_locales = [to_locales] unless to_locales.is_a?(Array)

  # for each provider
  #   get translations for all texts from the database
  #   for texts that are untranslated, call the provider
  # return translations

  translation_collection = Translation::Collection.new
  text_collection.each_locale do |from_locale, list|
    next if list.blank?
    @providers.each do |provider|
      to_locales.each do |to_locale|
        fetcher = Translation::Fetcher.new(
          provider: provider, texts: list, use_db: @use_db,
          from_locale: from_locale, to_locale: to_locale,
          listener: @listener
        )
        translations = fetcher.translations
        translation_collection += translations
        update_stats(translations)
      end
    end
  end

  combine_substrings(translation_collection, text_collection, to_locales)
  translation_collection
end