Class: I18nTranslationGenerator

Inherits:
Rails::Generators::NamedBase
  • Object
show all
Defined in:
lib/generators/i18n_translation/i18n_translation_generator.rb

Instance Method Summary collapse

Instance Method Details

#mainObject

option: include_timestamps



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
# File 'lib/generators/i18n_translation/i18n_translation_generator.rb', line 6

def main
  unless file_name =~ /^[a-zA-Z]{2}([-_][a-zA-Z]+)?$/
    log 'ERROR: Wrong locale format. Please input in ?? or ??-?? format.'
    exit
  end
  log "translating models to #{locale_name}..."
  I18n.locale = locale_name
  if Rails.try(:autoloaders).try(:zeitwerk_enabled?)
    Zeitwerk::Loader.eager_load_all
  else
    Rails.application.eager_load!
  end

  # activerecord:models comes first
  model_names_translations = order_hash translate_all(model_names_keys)
  # activerecord:models:attributes comes next
  attribute_names_translations = ActiveSupport::OrderedHash.new
  attribute_names_translations.merge! translate_all(content_column_names_keys)
  attribute_names_translations.merge! translate_all(collection_reflection_names_keys)
  # refer to already translated model names
  attribute_names_translations.merge! singular_reflection_names_references
  # merge them all
  translations = model_names_translations.deep_merge order_hash(attribute_names_translations)

  yaml = I27r::YamlDocument.load_yml_file "config/locales/translation_#{locale_name}.yml"
  each_value [], translations do |parents, value|
    if value.is_a?(String) || value.is_a?(Symbol)
      yaml[[locale_name.to_s] + parents] = value
    else
      value.each do |key, val|
        yaml[[locale_name.to_s] + parents + [key.to_s]] = val
      end
    end
  end

  unless (yaml_string = yaml.to_s(true)).blank?
    create_file "config/locales/translation_#{locale_name}.yml", yaml_string
  end
end