Class: CopycatTranslation

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/copycat_translation.rb

Class Method Summary collapse

Class Method Details

.export_yamlObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/models/copycat_translation.rb', line 40

def self.export_yaml
  translations = all.inject(Hash.new { |h, k| h[k] = {} }) do |export, translation|
    key_components = translation.key.split('.')
    key_tail = key_components.pop

    key_scope = key_components.inject(export[translation.locale]) do |scope, key|
      scope[key] ||= {}
    end

    key_scope[key_tail] = translation.value

    export
  end

  translations.to_yaml
end

.import_yaml(yaml) ⇒ Object



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
# File 'app/models/copycat_translation.rb', line 10

def self.import_yaml(yaml)
  locales = YAML.load(yaml)

  locales.each do |locale, translations|
    while !translations.empty?
      flattened_translations = {}

      translations.each_key do |key_component|

        translation_or_nesting = translations.delete(key_component)

        if translation_or_nesting.is_a?(Hash)
          translation_or_nesting.each do |key, value|
            flattened_translations["#{key_component}.#{key}"] = value
          end
        elsif translation_or_nesting.present?
          attributes = { key: key_component, locale: locale }

          record = where(attributes).first_or_initialize(attributes)
          record.value = translation_or_nesting

          record.save
        end
      end

      translations.merge!(flattened_translations)
    end
  end
end