Class: I18nDocs::TranslationFileExport

Inherits:
Object
  • Object
show all
Defined in:
lib/i18n_docs/translation_file_export.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_dir, source_file, output_dir, locales) ⇒ TranslationFileExport

Returns a new instance of TranslationFileExport.



5
6
7
8
9
10
11
12
13
# File 'lib/i18n_docs/translation_file_export.rb', line 5

def initialize(source_dir, source_file, output_dir, locales)
  @source_dir = source_dir
  @source_file = source_file

  @output_file = File.join(output_dir, source_file.gsub('.yml', '.csv'))
  @locales = locales.map(&:to_s)

  @translations = {}
end

Instance Attribute Details

#translationsObject

Returns the value of attribute translations.



3
4
5
# File 'lib/i18n_docs/translation_file_export.rb', line 3

def translations
  @translations
end

Instance Method Details

#exportObject



15
16
17
18
# File 'lib/i18n_docs/translation_file_export.rb', line 15

def export
  load_translations
  write_to_csv
end

#flatten_translations_hash(translations, parent_key = []) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/i18n_docs/translation_file_export.rb', line 53

def flatten_translations_hash(translations, parent_key = [])
  flat_hash = {}

  translations.each do |key, t|
    current_key = parent_key.dup << key
    if t.is_a?(Hash)
      # descend
      flat_hash.merge!(flatten_translations_hash(t, current_key))
    else
      # leaf -> store as value for key
      flat_hash[current_key.join('.')] = t
    end
  end
  flat_hash
end

#load_language(locale) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/i18n_docs/translation_file_export.rb', line 44

def load_language(locale)
  puts "    #{@source_file}: load translations for '#{locale}'"

  input_file = File.join(@source_dir, locale, @source_file)
  translations = {}
  translations = YAML.load_file(input_file) if File.exist?(input_file)
  translations[locale]
end

#load_translationsObject



37
38
39
40
41
42
# File 'lib/i18n_docs/translation_file_export.rb', line 37

def load_translations
  @locales.each do |locale|
    translation_hash = load_language(locale)
    @translations[locale] = flatten_translations_hash(translation_hash)
  end
end

#write_to_csvObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/i18n_docs/translation_file_export.rb', line 20

def write_to_csv
  main_locale = @locales.include?('en') ? 'en' : @locales.first

  puts "    #{@source_file}: write CSV to '#{@output_file}' \n\n"

  CSV.open(@output_file, 'wb') do |csv|
    csv << (['key'] + @locales)

    @translations[main_locale].keys.each do |key|
      values = @locales.map do |locale|
        @translations[locale][key]
      end
      csv << values.unshift(key)
    end
  end
end