Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dot notation keys to tree-structured YAML in Ruby

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.

like image 966
Lomefin Avatar asked May 25 '26 15:05

Lomefin


1 Answers

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
like image 151
Lomefin Avatar answered May 27 '26 05:05

Lomefin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!