Module: CopycatTranslation::Serialize

Included in:
CopycatTranslation
Defined in:
app/models/copycat_translation.rb

Instance Method Summary collapse

Instance Method Details

#export_yamlObject



28
29
30
31
32
33
34
35
# File 'app/models/copycat_translation.rb', line 28

def export_yaml
  hash = {}
  all.each do |c|
    next unless c.value
    hash_fatten!(hash, [c.locale].concat(c.key.split(".")), c.value)
  end
  hash.to_yaml
end

#hash_fatten!(hash, keys, value) ⇒ Object

("a"=>{"b"=>{"e"=>"f"}}, ["a","b","c"], "d") ----> "e"=>"f"}}



51
52
53
54
55
56
57
58
59
60
# File 'app/models/copycat_translation.rb', line 51

def hash_fatten!(hash, keys, value)
  if keys.length == 1
    hash[keys.first] = value
  else
    head = keys.first
    rest = keys[1..-1]
    hash[head] ||= {}
    hash_fatten!(hash[head], rest, value)
  end
end

#hash_flatten(hash) ⇒ Object

"b"=>"2"} ----> "foo.b"=>2



38
39
40
41
42
43
44
45
46
47
48
# File 'app/models/copycat_translation.rb', line 38

def hash_flatten(hash)
  result = {} 
  hash.each do |key, value|
    if value.is_a? Hash 
      hash_flatten(value).each { |k,v| result["#{key}.#{k}"] = v }
    else 
      result[key] = value
    end
  end
  result
end

#import_yaml(yaml) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'app/models/copycat_translation.rb', line 16

def import_yaml(yaml)
  hash = YAML.load(yaml)
  hash.each do |locale, data|
    hash_flatten(data).each do |key, value|
      c = where(key: key, locale: locale).first
      c ||= new(key: key, locale: locale) 
      c.value = value
      c.save
    end
  end
end