Class: Lit::Export

Inherits:
Object
  • Object
show all
Defined in:
lib/lit/export.rb

Class Method Summary collapse

Class Method Details

.call(locale_keys:, format:, include_hits_count: false) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/lit/export.rb', line 6

def self.call(locale_keys:, format:, include_hits_count: false)
  raise ArgumentError, 'format must be yaml or csv' if %i[yaml csv].exclude?(format)
  Lit.loader.cache.load_all_translations
  localizations_scope = Lit::Localization.active
  if locale_keys.present?
    locale_ids = Lit::Locale.where(locale: locale_keys).pluck(:id)
    localizations_scope = localizations_scope.where(locale_id: locale_ids) unless locale_ids.empty?
  end
  db_localizations = {}
  localizations_scope.find_each { |l| db_localizations[l.full_key] = l.translation }

  case format
  when :yaml
    exported_keys = Lit::Services::LocalizationKeysToHashService.call(db_localizations)
    exported_keys.to_yaml
  when :csv
    relevant_locales = locale_keys.presence || I18n.available_locales.map(&:to_s)
    CSV.generate do |csv|
      csv << ['key', *relevant_locales, ('hits' if include_hits_count)].compact
      keys_without_locales = db_localizations.keys.map { |k| k.gsub(/(#{relevant_locales.join('|')})\./, '') }.uniq
      keys_without_locales.each do |key_without_locale|
        # Here, we need to determine if we're dealing with an array or a scalar.
        # In the former case, for simplicity of editing (which is likely the main
        # intent when exporting translations to CSV), let's make the "array" be simulated
        # as a number of consecutive rows that have the same key.
        #
        # For example:
        #
        # key,en
        # date.abbr_month_names,     <-- in this case it's empty because that array has nothing at [0]
        # date.abbr_month_names,Jan
        # date.abbr_month_names,Feb
        # date.abbr_month_names,Mar
        # date.abbr_month_names,Apr
        # date.abbr_month_names,May
        # ...

        key_localizations_per_locale =
          relevant_locales.map { |l| Array.wrap(db_localizations["#{l}.#{key_without_locale}"]) }
        transpose(key_localizations_per_locale).each do |translation_series|
          csv_row = [key_without_locale, *translation_series]
          csv_row << (Lit.init.cache.get_global_hits_counter(key_without_locale) || 0) if include_hits_count
          csv << csv_row
        end
      end
    end
  end
end