Module: I18nTasksCsv

Includes:
I18n::Tasks::Command::Collection
Defined in:
lib/i18n-tasks-csv.rb

Constant Summary collapse

VERSION =
'1.1'

Instance Method Summary collapse

Instance Method Details

#csv_export(_opts = {}) ⇒ Object



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
# File 'lib/i18n-tasks-csv.rb', line 9

def csv_export(_opts = {})
  translations_by_path = {}
  router = I18n::Tasks::Data::Router::
    PatternRouter.new(nil, write: i18n.config['csv']['export'])

  i18n.locales.each do |locale|
    router.route(locale, i18n.data_forest) do |path, nodes|
      translations_by_path[path] ||= {}
      translations_by_path[path][locale] ||= {}

      nodes.leaves do |node|
        translations_by_path[path][locale][node.full_key(root: false)] =
          node.value
      end
    end
  end

  translations_by_path.each do |(path, translations_by_locale)|
    FileUtils.mkdir_p(File.dirname(path))

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

      translations_by_locale[i18n.base_locale].keys.each do |key|
        values = i18n.locales.map do |locale|
          translations_by_locale[locale][key]
        end
        csv << values.unshift(key)
      end
    end
  end
end

#csv_import(_opts = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/i18n-tasks-csv.rb', line 43

def csv_import(_opts = {})
  i18n.config['csv']['import'].each do |file|
    csv = open(file).read.force_encoding('UTF-8')

    translations = []
    CSV.parse(csv, headers: true) do |row|
      key = row['key']
      next unless key

      i18n.locales.each do |locale|
        unless row.key?(locale)
          fail "Locale missing for key #{key}! (locales in app: " \
            "#{locales} / locales in file: #{row.headers.inspect})"
        end
        translations << [[locale, key].join('.'), row[locale]]
      end
    end

    i18n.data.merge! \
      I18n::Tasks::Data::Tree::Siblings.from_flat_pairs(translations)
  end
end