class I18n::CsvTranslation::Importer

Public Class Methods

new(col_sep: ";") click to toggle source
# File lib/i18n/csv_translation/importer.rb, line 6
def initialize col_sep: ";"
  @col_sep = col_sep
end

Public Instance Methods

import(input:, path:, new_locale: @input = input) click to toggle source
# File lib/i18n/csv_translation/importer.rb, line 10
def import input:, path:, new_locale:
  @input      = input
  @path       = path
  @new_locale = new_locale

  translations = load_translations_from_csv
  save_translations_as_yaml translations
end

Private Instance Methods

key_with_locale(key) click to toggle source
# File lib/i18n/csv_translation/importer.rb, line 58
def key_with_locale key
  "#{@new_locale}.#{key}"
end
load_translations_from_csv() click to toggle source
# File lib/i18n/csv_translation/importer.rb, line 21
def load_translations_from_csv
  translations = {}

  CSV.foreach(@input, col_sep: @col_sep) do |csv|
    unless csv[1].nil? && csv[2].nil?
      if translations[csv[0]].nil?
        translations[csv[0]] = { key_with_locale(csv[1]) => csv[2] }
      else
        translations[csv[0]].merge!({ key_with_locale(csv[1]) => csv[2] })
      end
    end
  end

  translations
end
save_translations_as_yaml(translations) click to toggle source
# File lib/i18n/csv_translation/importer.rb, line 37
def save_translations_as_yaml translations
  translations.each do |key, value|
    unless key.nil?
      filename = Pathname.new(@path).join("#{@new_locale}." + Pathname.new(key).basename.to_s)
      file = File.open(filename, "w")

      hash = {}

      value.each do |inner_key, inner_value|
        a = inner_key.split(".").reverse.inject(inner_value) { |a, n| { n => a } }
        hash.deep_merge! a
      end

      # TODO Add option to omit "header"
      file.write(hash.to_yaml)

      file.close
    end
  end
end