Class: RailsI18nOnair::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_i18n_onair/importer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locale_path = nil) ⇒ Importer

Returns a new instance of Importer.



9
10
11
12
13
14
# File 'lib/rails_i18n_onair/importer.rb', line 9

def initialize(locale_path = nil)
  @locale_path = locale_path || RailsI18nOnair.configuration.locale_files_path
  @imported_count = 0
  @skipped_count = 0
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



7
8
9
# File 'lib/rails_i18n_onair/importer.rb', line 7

def errors
  @errors
end

#imported_countObject (readonly)

Returns the value of attribute imported_count.



7
8
9
# File 'lib/rails_i18n_onair/importer.rb', line 7

def imported_count
  @imported_count
end

#locale_pathObject (readonly)

Returns the value of attribute locale_path.



7
8
9
# File 'lib/rails_i18n_onair/importer.rb', line 7

def locale_path
  @locale_path
end

#skipped_countObject (readonly)

Returns the value of attribute skipped_count.



7
8
9
# File 'lib/rails_i18n_onair/importer.rb', line 7

def skipped_count
  @skipped_count
end

Instance Method Details

#import_allObject

Import all locale files from the configured path (recursively). Files for the same language (en.yml, devise.en.yml, models/en.yml) are deep-merged into one record instead of overwriting each other.



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
# File 'lib/rails_i18n_onair/importer.rb', line 19

def import_all
  unless File.directory?(full_locale_path)
    raise Error, "Locale path does not exist: #{full_locale_path}"
  end

  locale_files = find_locale_files

  if locale_files.empty?
    raise Error, "No locale files found in: #{full_locale_path}"
  end

  locale_files.group_by { |path| extract_language_code(File.basename(path)) }.each do |language, files|
    merged = {}
    files.each do |file_path|
      data = YAML.load_file(file_path)
      merged.deep_merge!(data) if data.is_a?(Hash)
    end

    Translation.create_or_update_by_language(language, merged)
    @imported_count += files.count
  rescue => e
    @errors << { language: language, files: files, error: e.message }
    @skipped_count += files.count
  end

  {
    imported: @imported_count,
    skipped: @skipped_count,
    errors: @errors
  }
end