Class: RailsI18nManager::TranslationsImporter

Inherits:
Object
  • Object
show all
Defined in:
app/lib/rails_i18n_manager/translations_importer.rb

Defined Under Namespace

Classes: ImportAbortedError

Class Method Summary collapse

Class Method Details

.import(translation_app_id:, parsed_file_contents:, overwrite_existing: false, mark_inactive_translations: false) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/lib/rails_i18n_manager/translations_importer.rb', line 6

def self.import(translation_app_id:, parsed_file_contents:, overwrite_existing: false, mark_inactive_translations: false)
  app_record = TranslationApp.find(translation_app_id)

  new_locales = parsed_file_contents.keys - app_record.all_locales

  if new_locales.any?
    raise ImportAbortedError.new("Import aborted. Locale not listed in translation app: #{new_locales.join(', ')}")
  end

  all_keys = RailsI18nManager.fetch_flattened_dot_notation_keys(parsed_file_contents)

  key_records_by_key = app_record.translation_keys.includes(:translation_values).index_by(&:key)

  all_keys.each do |key|
    if key_records_by_key[key].nil?
      key_records_by_key[key] = app_record.translation_keys.new(key: key)
      key_records_by_key[key].save!
    end
  end

  translation_values_to_import = []

  key_records_by_key.each do |key, key_record|
    app_record.all_locales.each do |locale|
      split_keys = [locale] + key.split(".").map{|x| x}

      val = nil

      current_hash = parsed_file_contents

      split_keys.each do |k|
        if current_hash[k].is_a?(Hash)
          current_hash = current_hash[k]
        else
          val = current_hash[k]
          break
        end
      end

      if val.present?
        val_record = key_record.translation_values.detect{|x| x.locale == locale.to_s }

        if val_record.nil?
          translation_values_to_import << key_record.translation_values.new(locale: locale, translation: val)
        elsif val_record.translation.blank? || (overwrite_existing && val_record.translation != val)
          val_record.update!(translation: val)
          next
        end
      end
    end
  end

  ### We use active_record-import for big speedup, set validate false if more speed required
  TranslationValue.import(translation_values_to_import, validate: true)

  if mark_inactive_translations
    app_record.translation_keys
      .where.not(key: all_keys)
      .update_all(active: false)

    app_record.translation_keys
      .where(key: all_keys)
      .update_all(active: true)
  end

  return true
end