Convert dot notation keys to tree-structured YAML in Ruby

时间:2016-10-20 19:55:11

标签: ruby yaml rails-i18n

I've sent my I18n files to be translated by a third party. Since my translator is not computer savvy we made a spreadsheet with the keys, they where sent in dot notation and the values translated.

For example:

es.models.parent: "Pariente"
es.models.teacher: "Profesor"
es.models.school: "Colegio"

How can I move that into a YAML file?

UPDATE: Just like @tadman said, this already is YAML. So if you are with the, you are just fine.

So we will focus this question if you would like to have the tree structure for YAML.

1 个答案:

答案 0 :(得分:1)

The first thing to do is transform this into a Hash.

So the previous info moved into this:

tr = {}
tr["es.models.parent"]  = "Pariente"
tr["es.models.teacher"] = "Profesor"
tr["es.models.school"]  = "Colegio"

Then we just advanced creating a deeper hash.

result = {} #The resulting hash

tr.each do |k, value|
  h = result
  keys = k.split(".") # This key is a concatenation of keys
  keys.each_with_index do |key, index|
    h[key] = {} unless h.has_key? key
    if index == keys.length - 1 # If its the last element
      h[key] = value            # then we only need to set the value
    else
      h = h[key]
    end
  end
end;

require 'yaml'

puts result.to_yaml #Here it is for your YAMLing pleasure